sqlite实例代码
一、准备工作
sqlite正常安装,参考https://www.cnblogs.com/huang-y-x/p/10417050.html。
运行sqlite3能够显示sqlite的版本信息,拷贝好库文件到指定位置(libsqlite.so)、编译的时候指定链接路径和名称。
分别运行以下命令建立数据库和数据表:"sudo su"; "sqlite3 testsqlite3.db"; "CREATE TABLE user(id INTEGER PRIMARY KEY autoincrement, name TEXT NOT NULL, age INT NOT NULL, mobile CHAR(50));"。注意:Error: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
二、源文件,main.cpp
#include <iostream> #include <string> #include "sqlite3.h" using namespace std; static int callback(void *data,int args_num,char **argv,char **argc){ for(int i=0;i<args_num;i++){ cout<<argc[i]<<" = " <<(argv[i]?argv[i]:"NULL")<<"\t"; } cout<<endl; return 0; } int main(){ sqlite3 *db; char *errMsg; string sql = "insert into user (id, name,age,mobile) values (NULL,'xxx',20,'15011186301')"; int rc = sqlite3_open("./testsqlite3.db",&db); if(rc!=SQLITE_OK){ cout<<"open sqlite3 fail."<<endl; return -1; } cout<<"open sqlite3 ok."<<endl; int rs = sqlite3_exec(db,sql.c_str(),0,0,&errMsg); if(rs!=SQLITE_OK){ cout<<"insert fail:"<< errMsg <<endl; }else{ cout<<"insert data ok."<<endl; } sql = "select * from user"; int first = 0; sqlite3_exec(db,sql.c_str(),callback,(void *)&first,&errMsg); sqlite3_close(db); return 0; }
三、编译运行
命令:sudo g++ main.cpp -lsqlite3(生成a.out可执行文件)/sudo g++ main.cpp -lsqlite3 -o main(顺序不能换,生成main可执行文件)
运行结果显示如下:
坚持成就伟大