2011-02-10 62 views
0

人, 從下面的代碼什麼是C中mysql_query的返回錯誤值?

int a = mysql_query(conn,"INSERT into data VALUES (NULL,'tes','aja')); 

怎麼來的,我可以保證的mysql_query是做應該的事情,因爲我已經試過錯誤的SQL查詢,它的mysql_query功能變得相同的返回值

其中從文件mysql.h:

int  STDCALL mysql_query(MYSQL *mysql, const char *q); 

有沒有辦法來檢查查詢字符串是否有效,並正確查詢?

回答

0

我很驚訝我必須使用的MySQL數據庫沒有在「錯誤的查詢」上返回錯誤。 (MySQL數據庫不在我的管理範圍內)你不會寫出什麼確切的問題與你查詢;問題是什麼。我想我的問題可能與您的問題類似。

(實施例表被簡化。)

我的表 'T' 與COLS 'A' 的varchar [10]不爲空, 'B' VARCHAR [10]

int a = mysql_query(conn,"INSERT INTO T (B) VALUE ('data')"); 

問題結果是好的,錯誤信息是空的,只有一個警告出現。

解決方案不僅要測試錯誤,還要測試警告。

if (mysql_errno(conn) || mysql_warning_count(conn)) 
    result = 1; //error 
else 
    result = 0; //OK 

如果你需要顯示警告/錯誤還有就是我的簡單示例代碼:

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); 
} 

我需要處理所有給定的數據必須是正確的,並沒有丟失。缺少數據(根據表定義)是不可接受的;數據修整('ABC12345678'改爲'ABC1234567')也是不可接受的。這兩個問題都僅作爲警告處理。因此,我將所有警告視爲錯誤。