folks, from the following code
int a = mysql_query(conn,"INSERT into data VALUES (NULL,'tes','aja'));
how come i could make sure mysql_query is do the sup开发者_如何学编程posed thing, because i've tried wrong sql query and it becomes same return value
from mysql_query function which from file mysql.h:
int STDCALL mysql_query(MYSQL *mysql, const char *q);
is there a way to check that string of query is valid and queried properly ?
According to the MySQL reference documentation for mysql_query this should return zero on success and non-zero on failure. Are you sure that it is returning 0 value for an invalid query?
I was surprised that the MySQL database I had to use did not return error on "wrong query". (The MySQL database is not in my administration) You do not write what exact problem do you have with you query; what is the problem. I suppose my problem can be similar to your problem.
(Example table is simplified.)
My table 'T' with cols 'A' varchar[10] not null, 'B' varchar[10]
int a = mysql_query(conn,"INSERT INTO T (B) VALUE ('data')");
The problem is that the result is OK, error message is empty and only one warning is present.
Solution is to test not only error but also warnings.
if ( mysql_errno( conn ) || mysql_warning_count( conn ) )
result = 1; //error
else
result = 0; //OK
If you need to display warnings/errors there is my simple sample code:
static void display_warnings( MYSQL *conn )
{
MYSQL_RES *sql_result;
MYSQL_ROW row;
if ( ( conn == NULL ) || mysql_query( conn, "SHOW WARNINGS" ) )
{
printf( "Can not display list of errors/warnings!\n" );
return;
}
sql_result = mysql_store_result( conn );
if ( ( sql_result == NULL ) || ( sql_result->row_count == 0 ) )
{
printf( "Can not display list of errors/warnings!\n" );
if ( sql_result )
mysql_free_result( sql_result );
return;
}
row = mysql_fetch_row( sql_result );
if ( row == NULL )
{
printf( "Can not display list of errors/warnings!\n" );
mysql_free_result( sql_result );
return;
}
do
{
// Format: "message [Type: number]"
printf( "%s [%s: %s]\n", row[2], row[0], row[1] );
row = mysql_fetch_row( sql_result );
} while ( row );
mysql_free_result( sql_result );
}
I need to handle that all given data must be correct and none is missing. Missing data (according to table definition) is unacceptable; trimming of data ('ABC12345678' changed to 'ABC1234567') is also unacceptable. Both these problems are handled only as warning. Therefore I handle all warnings as errors.
精彩评论