0.下载
1.创建测试库数据
BEGIN
TRANSACTION;
CREATE TABLE sdns (id INTEGER PRIMARY KEY,name TEXT,ip TEXT);
INSERT INTO sdns VALUES(1,'UNI-BJ-SDNS','1.2.3.4');
INSERT INTO sdns VALUES(2,'CTC-GD-SDNS','5.6.7.8');
COMMIT;
CREATE TABLE sdns (id INTEGER PRIMARY KEY,name TEXT,ip TEXT);
INSERT INTO sdns VALUES(1,'UNI-BJ-SDNS','1.2.3.4');
INSERT INTO sdns VALUES(2,'CTC-GD-SDNS','5.6.7.8');
COMMIT;
2.创建测试程序
//gcc sqlite3.c test.c -o t -lpthread -ldl
//./t test.db "select * from sdns"
#include <stdlib.h>
#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]);
exit(1);
}
//打开数据库
rc = sqlite3_open(argv[1],&db);
if( rc ){
//执行出错,关闭数据库
fprintf(stderr,"Can't open database: %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db,argv[2],callback,&zErrMsg);
if( rc!=sqlITE_OK ){
//打印错误信息
fprintf(stderr,"sql error: %s\n",zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
//./t test.db "select * from sdns"
#include <stdlib.h>
#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]);
exit(1);
}
//打开数据库
rc = sqlite3_open(argv[1],&db);
if( rc ){
//执行出错,关闭数据库
fprintf(stderr,"Can't open database: %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db,argv[2],callback,&zErrMsg);
if( rc!=sqlITE_OK ){
//打印错误信息
fprintf(stderr,"sql error: %s\n",zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
gcc sqlite3.c test.c -o t -lpthread -ldl
[root@localhost sqlite]# ./t test.db "select * from sdns"
id = 1
name = UNI-BJ-SDNS
ip = 1.2.3.4
id = 2
name = CTC-GD-SDNS
ip = 5.6.7.8
id = 1
name = UNI-BJ-SDNS
ip = 1.2.3.4
id = 2
name = CTC-GD-SDNS
ip = 5.6.7.8
end
原文链接:https://www.f2er.com/sqlite/202599.html