方式一:利用回调函数callback
int sqlite3_exec(sqlite3*, const char *sql,sqlite3_callback, void *,char **errmsg);
int callback(void*para , int nCount, char** pValue, char** pName) {
/*****************************************************************************
sqlite 每查到一条记录,就调用一次这个回调
para是你在 sqlite3_exec 里传入的 void * 参数, 通过para参数,你可以传入一些特殊的指针(比如类指 针、结构指针),然后在这里面强制转换成对应的类型(这里面是void*类型,必须强制转换成你的类型才可用)。然后操作这些数据
nCount是这一条(行)记录有多少个字段 (即这条记录有多少列)
char ** pValue 是个关键值,查出来的数据都保存在这里,它实际上是个1维数组(不要以为是2维数组),每一个元素都是一个 char* 值,是一个字段内容(用字符串来表示,以/0结尾)
char ** pName 跟pValue是对应的,表示这个字段的字段名称, 也是个1维数组
*****************************************************************************/
string s;
for(int i=0;i<nCount;i++){
s+=pName[i];
s+=":";
s+=pValue[i];
s+="\n";
}
cout<<s<<endl;
return 0;
}
方式二:sqlite3_get_table
int sqlite3_get_table(sqlite3*, const char *sql, char ***resultp, int *nrow, int *ncolumn, char **errmsg);
string strSql = "select * from MyTable";
char** pResult;
int nRow;
int nCol;
nResult = sqlite3_get_table(db,strSql.c_str(),&pResult,&nRow,&nC,&errmsg);
if (nResult != SQLITE_OK)
{
sqlite3_close(db);
cout<<errmsg<<endl;
sqlite3_free(errmsg);
return 0;
}
string strOut;
int nIndex = nCol;
for(int i=0;i<nRow;i++)
{
for(int j=0;j<nCol;j++)
{
strOut+=pResult[j];
strOut+=":";
strOut+=pResult[nIndex];
strOut+="\n";
++nIndex;
}
}
sqlite3_free_table(pResult); //使用完后务必释放为记录分配的内存,否则会内存泄漏
cout<<strOut<<endl;
sqlite3_close(db);
return 0;
}
方式三:通过sqlite3_prepare、sqlite3_step一系列操作
//查询所有数据
sqlite3 *db;
sqlite3_stmt * stmt = NULL;
const char *zTail;
int r =sqlite3_open("mysqlite.db",&db) //打开数据库
if (sqlite3_prepare_v2(db,
"SELECT ID, name, num FROM players;", -1, &stmt, &zTail) ==SQLITE_OK){
while( sqlite3_step(stmt) ==SQLITE_ROW ) {
int id =sqlite3_column_int( stmt, 0);
constunsigned char * name = sqlite3_column_text( stmt,1);
intnumber = sqlite3_column_int( stmt, 2);
printf("ID: %d Name: %s Age: %d /n",id,name,number);
}
}
sqlite3_finalize(stmt);
//关闭数据库
sqlite3_close(db);
方式四:利用事务(BEGIN;COMMIT;)批量操作
//插入条数据(在Begin和Commit之间批量操作,可以大幅度提高效率)
result =sqlite3_exec(db, "BEGIN;",0, 0, 0);
for (int i=0; i<10000; i++)
{
//插入一条数据
result = sqlite3_exec(db,
"INSERT INTOMyTable (MyText, MyDate, MyTime, MyFloat) VALUES ('---上班好远!', '2012-03-23', '9:00:00', 1000);",
0, 0, 0);
}
result =sqlite3_exec(db, "COMMIT;",0, 0, 0); .
string strSql;
strSql+="begin;\n";
for (int i=0;i<100;i++)
{
strSql+="insert into MyTable values(null,'heh');\n";
}
strSql+="commit;";
//cout<<strSql<<endl;
nResult = sqlite3_exec(db,strSql.c_str(),NULL,NULL,&errmsg);