2012-03-19 81 views
1

我在寫C程序來訪問數據庫。 我最近從sqlite切換到mysql。 我不熟悉mysql c api,所以我需要幫助轉換一些代碼。最近從sqlite切換到mysql。需要轉換一些代碼c

下面的例子是用參數執行sql語句。

源碼:

char *zSQL = sqlite3_mprintf("SELECT price FROM warehouse WHERE p_ID='%q'", input_value); 
sqlite3_prepare_v2(handle,zSQL,-1,&stmt,0); 

我嘗試在MySQL:

char zSQL[60] = {'\0'}; 
int n = 0; 

n = sprintf(zSQL, "SELECT price FROM warehouse WHERE p_ID='%s'", input_value); 
mysql_real_query(conn, zSQL, n); 

另一個例子是解析SQL語句的結果變量

源碼:

double price_value = 0; 
if (sqlite3_step (stmt) == SQLITE_ROW) { 
    price_value = sqlite3_column_double (stmt, 0); 
} 

的mysql:

MYSQL_ROW row; 
while ((row = mysql_fetch_row(result))) 
{ 
    price_value = atof(row[0]); 
} 

雖然在MySQL的代碼對我的作品,但我覺得我沒有利用API就夠了。 mysql c api中是否有與sqlite3_mprintf()sqlite3_column_double()具有相同功能的函數?

編輯: 我對mysql_real_escape_string()嘗試:

ulong in_length = strlen(input_value); 
char input_esc[(2 * in_length)+1]; 

mysql_real_escape_string(conn, input_esc, input_value, in_length); 
char sql_stmnt[56] = {'\0'}; 

n = sprintf(zSQL, "SELECT price FROM warehouse WHERE p_ID='%s'", input_esc); 
mysql_real_query(conn, sql_stmnt, n); 

回答

0

關於你的第exampe,簡單的答案是否定的,你必須自己做,看到http://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html

unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length) 

第二個,是的,這是要走的路,有一些額外的檢查,row[0]確實是雙重類型。

或者,您可以使用準備好的聲明API,它與sqlite3中的聲明非常相似。關鍵是你提供MYSQL_BIND類型的緩衝區,然後將輸入綁定到它,或者在那裏有mysql綁定輸出值。

準備語句文檔:http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-data-structures.html

+0

我發現這個[示例](http://mysqlresources.com/api/c/690)。這和我的很相似。我可以只'mysql_real_escape_string()''input_value'嗎? – 2012-03-20 04:42:50

+0

看看我的帖子,在'mysql_real_escape_string()' – 2012-03-20 05:23:06

+0

是我的嘗試,這看起來是對的 – hroptatyr 2012-03-20 07:36:14