C++对SQLite进行操作的代码如下:
#include "stdafx.h"
#include <string.h>
using namespace std;
#include "sqlite3.h"
#pragma comment(lib, "SQLITE3.LIB")
static int SelectCallback(void *notUsed, int argc, char **argv, char **azColName)
{
for (int i = 0 ; i < argc ; i++)
{
printf("%s = %s", azColName[i], (argv[i] ? argv[i] : "NULL"));
if (i != argc -1)
{
printf(", ");
}
}
printf("\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
sqlite3 * pDB;
char* errMsg;
// 打开SQLite数据库
int res = sqlite3_open("sql.db", &pDB);
if ( res != SQLITE_OK ){
printf("Can't open database: %s\n", sqlite3_errmsg(pDB));
sqlite3_close(pDB);
return -1;
}
// 创建表
string strSQL= "create table test (id int, name text);";
res = sqlite3_exec(pDB , strSQL.c_str() ,0 ,0, &errMsg);
if (res != SQLITE_OK)
{
printf("Create table error: %s\n", errMsg);
//return -1;
}
// 插入数据
res = sqlite3_exec(pDB,"begin transaction;",0,0, &errMsg);
for (int i= 1; i < 10; ++i)
{
char sql[512];
sprintf_s(sql, "insert into test values(%d, %s);", (i+10), "\"Test Name\"");
res = sqlite3_exec(pDB, sql,0,0, &errMsg);
if (res != SQLITE_OK)
{
printf("Insert error: %s\n", errMsg);
return -1;
}
}
res = sqlite3_exec(pDB,"commit transaction;",0,0, &errMsg);
// 查询数据
strSQL= "select * from test;";
res = sqlite3_exec(pDB, strSQL.c_str(), SelectCallback, 0 , &errMsg);
if (res != SQLITE_OK)
{
printf("Select error: %s\n", errMsg);
return -1;
}
// 关闭数据库
sqlite3_close(pDB);
return 0;
}
- 欢迎访问木庄网络博客
- 可复制:代码框内的文字。
- 方法:Ctrl+C。