首先是一个简单的应用:
test_sqlite.c
#include <stdio.h> #include <sqlite3.h> static int callback(void *NotUsed,int argc,char **argv,char **azColName) { int i; for(i=0; i<argc; i++) { printf("%s = %s/n",azColName[i],argv[i] ? argv[i] : "NULL"); } printf("/n"); return 0; } int main(int argc,char **argv) { sqlite3 *db; char *zErrMsg = 0; int rc; if( argc!=3 ) { fprintf(stderr,"Usage: %s DATABASE sql-STATEMENT/n",argv[0]); } rc = sqlite3_open(argv[1],&db); if( rc ) { fprintf(stderr,"Can't open database: %s/n",sqlite3_errmsg(db)); sqlite3_close(db); } rc = sqlite3_exec(db,argv[2],callback,&zErrMsg); if( rc!=sqlITE_OK ) { fprintf(stderr,"sql error: %s/n",zErrMsg); } sqlite3_close(db); return 0; }编译语句:arm-linux-gcc -o test_sqlite test_sqlite.c -lsqlite3 -L/home/bks/sqlite3/lib -I/home/bks/sqlite3/include
需要加入lib和include的路径。
编译完成后使用语句:./test_sqlite test.db "SELECT * FROM phonetable"
这里需要注意的是:我之前在当前目录文件夹下建立了名字:test.db 的数据库,其中包含表格:phonetable
现在是一个高级运用啦:
#include <stdio.h> #include "sqlite3.h" static int callback(void *NotUsed,int ncols,char **values,char **headers) { int i; for(i=0; i<ncols; i++) { printf("%s = %s\n",headers[i],values[i] ? values[i] : "NULL"); } printf("\n"); return 0; } void doCmd(sqlite3 *db,char *pCmd) { char *errmsg=NULL; if (sqlite3_exec(db,pCmd,NULL,&errmsg) != sqlITE_OK) { printf("%s\n",errmsg); return; } } int main() { sqlite3 *db = NULL; char *errmsg=NULL; printf("Please input the name of DB(*.db):\n"); char dbname[30]; gets(dbname); //Open a DB int result = sqlite3_open(dbname,&db); if (result != sqlITE_OK) { sqlite3_close(db); return; } //Create a Table char *createTablesql = "CREATE TABLE IF NOT EXISTS PHONETABLE (id integer primary key,name text,phone_number integer)"; doCmd(db,createTablesql); printf("Succeed to create test table now.\n"); //Insert char *sql=NULL; sql="INSERT into PHONETABLE (name,phone_number) values('Jone','15901110265')"; doCmd(db,sql); sql="INSERT into PHONETABLE (name,phone_number) values('Jack','13811907568')"; doCmd(db,sql); doCmd(db,"INSERT into PHONETABLE (name,phone_number) values('Jackson','13811907568')"); //Show printf("Show the table\n"); sql="SELECT *FROM PHONETABLE"; int rc = sqlite3_exec(db,sql,&errmsg); if( rc!=sqlITE_OK ) { fprintf(stderr,"sql error: %s\n",errmsg); } //Delete printf("Delete 'Jack' from table\n"); sql="DELETE FROM phonetable where name='Jack'"; doCmd(db,sql); printf("Show the table\n"); sql="SELECT *FROM PHONETABLE"; rc = sqlite3_exec(db,errmsg); } //Change printf("Alter Jackson to Mike.\n"); sql="update phonetable set name='Jack' where name='Jone'"; doCmd(db,errmsg); } sqlite3_close(db); return 0; }
这个属于升级版了。操作包括了
1.建立数据库;
2.插入数据;
3.删除数据;
4.修改数据;
5.以及查询数据;
各位看官自己慢慢看吧。
就到这里,后续有新的研究成果在写出来