Database error when creating entities using hook_update_N I'm trying to create an entity (using entity-&gt;save()) in a hook_update_N function. The errors appear at the mysql insert query in the entity's insert function; the insert strings are wrapped in mysql_real_escape_string().

I get a series of warnings:

mysql_real_escape_string(): A link to the server could not be established mod_person.entity.inc:402

mysql_real_escape_string(): Access denied for user 'xxx'@'localhost' (using password: NO) mod_person.entity.inc:403


Followed by the error:

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'val' at row 1 


When I remove the mysql_real_escape_string() from the mysql insert query code it works! However now I'm worried that leaves the server vulnerable.

My questions are:

[1] Why does using mysql_real_escape_string() work in normal site operation and not through hook_update_N?

[2] Do I need to use mysql_real_escape_string() with Drupal 7 database queries or is there another way?

I suppose I could remove the mysql_real_escape_string() for the update and then put them back but that feels like I'm missing the point somewhere.

Many thanks for any help.
Similar to what Clive said, you will want to use the Database API (db_update, db_insert) or use an Entity Metadata wrapper.