使用C語言往數據庫中插入一個記錄,發現無論如何都無法插入。
數據庫的創建語法
int rc = sqlite3_exec(db, "create table if not exists \
Account_Blob(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
content BLOB, accountId TEXT NOT NULL);", NULL, NULL, &zErrMsg);
數據庫的插入語法
sqlite3_stmt *stmt;
sprintf(sql, "insert into Account_Blob(id, content, accountId) values(NULL, ?, %s);", account->id);
printf("%s\n", sql);
sqlite3_prepare(db, sql, -1, &stmt, 0);
sqlite3_bind_blob(stmt, 1, account, sizeof(tSimpleAccount), NULL);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
測試的 時候,發現能夠生成記錄:
tSimpleAccount account1;
sprintf(account1.name, "張三");
sprintf(account1.id, "001");
InsertBlobData(&account1);
但是在業務處理中,發現無法插入記錄:
tSimpleAccount account1;
sprintf(account1.name, "張三");
sprintf(account1.id, "default_id");
InsertBlobData(&account1);
把整個數據庫和賬號抽出來驗證。發現還是解決不了問題。
後來發現,是數據庫插入語句有問題:
sprintf(sql, "insert into Account_Blob(id, content, accountId) values(NULL, ?, %s);", account->id);
%s沒有添加引號(’%s’)。所以生成的sql字符串中,對應的是非字符的量,導致數據庫insert失敗。測試的時候能夠成功,是因爲測試數據是數字字符串。SQLite支持列的親和類型概念。任何列仍然可以存儲任何類型的數據,當數據插入時,該字段的數據將會優先採用親緣類型作爲該值的存儲方式。
就是把數字轉換成了字符串。
粗心導致的時間流失。