SQLite3使用筆記(2)——插入
1. 論述
如同上一篇文章SQLite3使用筆記(1)——查詢所述,使用SQLite進(jìn)行查詢操作同樣有兩種方式。對(duì)于比較簡(jiǎn)單的表格插入,使用sqlite3_exec()接口就可以了:
string strSql = "";
strSql += "insert into user(name,age)";
strSql += "values('";
strSql += sName;
strSql += "',";
strSql += sAge;
strSql += ");";
char* cErrMsg;
int nRes = sqlite3_exec(pDB, strSql.c_str(), 0, 0, &cErrMsg);
if (nRes != SQLITE_OK) {
cout << "add user fail: " << cErrMsg << endl;
return false;
} else {
cout << "add user success: " << sName.c_str() << "\t" << sAge.c_str()
<< endl;
}
sqlite3_free(cErrMsg);
但是對(duì)于一些比較復(fù)雜的情況,比如插入一個(gè)BLOB類型的數(shù)據(jù),更加推薦使用編譯statement,然后傳遞參數(shù)的辦法:
sqlite3_stmt *stmt = nullptr;
char sqlStr[256] = { 0 };
sprintf(sqlStr, "insert into tiles(zoom_level, tile_column, tile_row, tile_data) "
"values(%d, %d, %d, ?)", zi, xi, yi);
int rc = sqlite3_prepare_v2(pDB, sqlStr, -1, &stmt, NULL);
if (rc != SQLITE_OK)
{
cerr << "prepare failed: " << sqlite3_errmsg(pDB) << endl;
return;
}
else
{
// SQLITE_STATIC because the statement is finalized
// before the buffer is freed:
rc = sqlite3_bind_blob(stmt, 1, buffer, size, SQLITE_STATIC);
if (rc != SQLITE_OK)
{
cerr << "bind failed: " << sqlite3_errmsg(pDB) << endl;
}
else
{
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
{
cerr << "execution failed: " << sqlite3_errmsg(pDB) << endl;
}
}
}
sqlite3_finalize(stmt);
sqlite3_prepare_v2()編譯的sql語(yǔ)句中的?代表一個(gè)參數(shù),通過(guò)sqlite3_bind_blob()進(jìn)行綁定。sqlite3_bind_X也是一系列的函數(shù),blob表示綁定的是一個(gè)二進(jìn)制流,這個(gè)二進(jìn)制buffer最終通過(guò)執(zhí)行sqlite3_step()后插入到數(shù)據(jù)庫(kù)中。由于插入操作只有一次,所以第一次就會(huì)返回SQLITE_DONE,不用像查詢操作那樣迭代遍歷。
2. 總結(jié)
無(wú)論查詢和插入,都可以使用sqlite3_exec()這樣的簡(jiǎn)易接口,或者使用編譯statement然后執(zhí)行兩種方式。個(gè)人感覺(jué)非常像JDBC中Statement和Preparement,一種是直接拼接執(zhí)行,一種是預(yù)編譯后傳參執(zhí)行。當(dāng)然更加推薦使用編譯后執(zhí)行傳參的方式,效率高,控制度更細(xì)一點(diǎn),能預(yù)防SQL注入。

浙公網(wǎng)安備 33010602011771號(hào)