目标:使用c代码创建新数据库,包含表与数据
#include "sqlite3.h"
int sqlite3_exec(sqlite3*, const char *sql, int (*callback)(void*para,int argc,char**argv,char**argv_name), void *para,char **errmsg)
2.说明
第一个参数sqlite3*是打开的数据库;
第二个参数const char *sql是要执行的sql语句;
第三个参数int (*callback)(void*para,int argc,char**argv,char**argv_name)是回调函数;
第四个参数void *para是传递给回调函数的参数
第五个参数char **errmsg是如果sqlite3_exec函数执行发生错误返回的错误信息;
执行成功返回SQLITE_OK (0),否则返回其他值。
?
回调函数是用户自定义的,格式如下:
int callback(void*para,int argc,char**argv,char**argv_name)
{
/*回调函数功能*/
}
create table stu2(id Integer,name char,score Integer);
insert into stu values(18130106,'huang',99);
insert into stu2 values(18130101,"gang",100); ''和""都行
insert into stu(name,score) values("huanggang",98); 插入部分字段内容
select * from stu; //查询所有字段的结果
select name,score from stu; //查询数据库中部分字段的内容
delete from stu where id = 18130101;
update stu set name = 'huangg' where id = 18130106;
drop table stu;
alter table stu add column sex char;
代码:
#include <stdio.h>
2 #include <sqlite3.h>
3
4 int callback(void *arg, int column_size, char *column_value[],char *column_name[])
5 {
6
7 int i;
8 printf("arg = %s\n",(char *)arg);
9 for(i=0;i<column_size;i++){
10 printf("%s = %s\n",column_name[i],column_value[i]);
11 printf("------------\n");
12 }
13 printf("================================\n");
14 return 0;
15 }
16
17
18 int main(char argc ,char **argv)
19 {
20
21 sqlite3 *db;
22 int ret;
23 char *erroMes = NULL;
24
25 if(argc<2){
26 printf("pro: %s lack xxx.db\n",argv[0]);
27 return -1;
28
29 }
30
31 ret = sqlite3_open(argv[1],&db);
32
33 if(ret == SQLITE_OK){
34 printf("creat %s ok\n",argv[1]);
35 }else{
36 printf("erro:%s erro num %d\n",sqlite3_errmsg(db),ret);
37 }
38
39 /*sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char
40 **errmsg)*/
41 ret = sqlite3_exec(db,"create table Class01(id Integer, name char, score Integer);",callback,"content of sql:",&erroMes);
42 if(ret != SQLITE_OK){
43 printf("create table errro: %s\n",erroMes);
44 }
45
46 ret = sqlite3_exec(db,"insert into Class01 values(12580,'cao',991);",callback,"content of sql:",&erroMes);
47
48 if(ret != SQLITE_OK){
49 printf("insert errro: %s\n",erroMes);
50 }
51
运行结果: