1. 程式人生 > >SQLite第五課 應用案例

SQLite第五課 應用案例

sqlite 應用 案例

1 打開數據庫文件

sqlite3* m_db = NULL;

int ret = sqlite3_open_v2("test.db", &db, SQLITE_OPEN_READWRITE, NULL);

if (ret != SQLITE_OK)

{

return;

}


2 如果表不存在,創建表

char szCreateUserDataSql[1024] = "create table if not exists tb_user (id INTEGER ,\

type INTEGER,\

kind INTEGER)";


3 創建唯一的主鍵ID

char szCreateUserDataSql[1024] = "create table if not exists tb_user (id INTEGER PRIMARY KEY AUTOINCREMENT,\

type INTEGER,\

kind INTEGER)";


4 查詢

char szSql[1024] = {0};

sprintf(szSql, "select distinct * from tb_test");

sqlite3_stmt* stmt = NULL;

sqlite3_prepare(m_db, szSql, -1, &stmt, 0);

while (sqlite3_step(stmt) == SQLITE_ROW)

{

const unsigned char* szPOIName = sqlite3_column_text(stmt, 0);

char szName[128] = {0};

if (szPOIName)

{

sprintf(szName, "%s", szPOIName);

}

int kx = sqlite3_column_int(stmt, 3);

float x = sqlite3_column_double(stmt, 5);

}

sqlite3_finalize(stmt);


5 獲取sql執行失敗的錯誤信息

char* errMsg = NULL;

char* szSql = "select * from address";

nRet = sqlite3_exec(pDB, szSql, NULL, NULL ,&errMsg);

if (nRet != SQLITE_OK)

{

cout<<errMsg<<endl;

sqlite3_free(errMsg);

}

註意:釋放errMsg指向的內存

6 關閉數據庫

sqlite3_close(db);


SQLite第五課 應用案例