天天看點

SQLite3使用筆記(2)——插入

詳細介紹了使用SQLite3進行資料庫插入的操作。

目錄

  • 1. 論述
  • 2. 總結

1. 論述

如同上一篇文章SQLite3使用筆記(1)——查詢所述,使用SQLite進行查詢操作同樣有兩種方式。對于比較簡單的表格插入,使用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);
           

但是對于一些比較複雜的情況,比如插入一個BLOB類型的資料,更加推薦使用編譯statement,然後傳遞參數的辦法:

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語句中的?代表一個參數,通過sqlite3_bind_blob()進行綁定。sqlite3_bind_X也是一系列的函數,blob表示綁定的是一個二進制流,這個二進制buffer最終通過執行sqlite3_step()後插入到資料庫中。由于插入操作隻有一次,是以第一次就會傳回SQLITE_DONE,不用像查詢操作那樣疊代周遊。

2. 總結

無論查詢和插入,都可以使用sqlite3_exec()這樣的簡易接口,或者使用編譯statement然後執行兩種方式。個人感覺非常像JDBC中Statement和Preparement,一種是直接拼接執行,一種是預編譯後傳參執行。當然更加推薦使用編譯後執行傳參的方式,效率高,控制度更細一點,能預防SQL注入。