Name

mysql_real_query( )

Synopsis

int mysql_real_query(MYSQL *mysql, const char *query, 
                     unsigned int length)

Use this to execute the SQL query given as the second argument of the function. Only one SQL statement may be given. Unlike mysql_query( ), this function can execute queries containing binary data. Because of this feature, the number of bytes contained in the query needs to be given for the third argument. This can be determined with the C function strlen( ). If successful, the function will return 0; otherwise, nonzero.

...
mysql = mysql_init(NULL);
mysql_real_connect(mysql,host,user,password,database,port,socket,flag);
const char *sql_stmnt = "SELECT * FROM stores";
ulong bytes = strlen(sql_stmnt);
mysql_real_query(mysql, sql_stmnt, bytes);
result = mysql_store_result(mysql);
num_fields = mysql_field_count(mysql);
while((row = mysql_fetch_row(result)) != NULL)
  {
   for(i = 0; i < num_fields; i++)
     { printf("%s, ", row[i]); }
   printf("\n");
  }
...

In this example, the number of bytes of the variable containing the SQL statement is determined with the C function strlen( ) and is stored in a separate variable called bytes. In turn, the bytes variable is given as the third argument to the mysql_real_query( ) function. As an alternative, strnlen(sql_stmnt) could be given as the third argument instead.

Get MySQL in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.