C语言操作sqlite3数据库注意SQL语言中字符串的处理

使用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支持列的亲和类型概念。任何列仍然可以存储任何类型的数据,当数据插入时,该字段的数据将会优先采用亲缘类型作为该值的存储方式。

就是把数字转换成了字符串。

粗心导致的时间流失。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章