C实现创建表

实现之前需要了解几个API

sqlite3_exec(

sqlite3*, // 第一个参数 sqlite3 是打开的数据库对象

const char *sql, // 需要执行的sql语句

sqlite_callback, // 一个回调,表里面有几条数据,就会执行几次

void *data, // data 作为sqlite_callback 的第一个参数

char **errmsg // 将被返回用来获取程序生成的任何错误。

)

sqlite3_exec():程序解析并执行由 sql 参数所给的每个命令,直到字符串结束或者遇到错误为止。

int callback(

void *arg, // 是sqlite3_exec函数的第四个参数

int column_size, // 数据库的字段数

char *column_value[], // 列的值

char *column_name[] // 字段名字

)

#include

#include

int callback(void *arg, int column_size, char *column_value[], char *column_name[])

{

printf("arg = %s\n", (char *)arg);

int i;

for(i = 0; i < column_size; i++){

printf("%s = %s\n", column_name[i], column_value[i]);

}

printf("===============\n");

return 0; //必须返回0,这样数据库中有多少条数据,这个回调函数就会被调用多少次

}

int main(char argc, char **argv)

{

sqlite3 *db;

char *errorMsg = NULL;

int ret;

if(argc < 2){

printf("Usage: %s xxx.db\n", argv[0]);

return -1;

}

if((ret = sqlite3_open(argv[1], &db)) == SQLITE_OK){

printf("open %s success\n",argv[1]);

}else{

if(ret == 14){

printf("permission den\n");

}

return -1;

}

// sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

sqlite3_exec(db, "select * from stu;", callback, "context sqlite...", &errorMsg);

sqlite3_close(db);

printf("done\n");

return 0;

}

3 插入数据的C接口

#include

#include

int callback(void *arg, int column_size, char *column_value[], char *column_name[])

{

printf("arg = %s\n", (char *)arg);

int i;

for(i = 0; i < column_size; i++){

printf("%s = %s\n", column_name[i], column_value[i]);

}

printf("===============\n");

return 0;

}

int main(char argc, char **argv)

{

sqlite3 *db;

char *errorMsg = NULL;

int ret;

if(argc < 2){

printf("Usage: %s xxx.db\n", argv[0]);

return -1;

}

if((ret = sqlite3_open(argv[1], &db)) == SQLITE_OK){

printf("open %s success\n",argv[1]);

}else{

if(ret == 14){

printf("permission den\n");

}

return -1;

}

// sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

ret = sqlite3_exec(db, "create table Class01(id Integer,name char,score Integer);",\

callback, "context sqlite...", &errorMsg);

if(ret != SQLITE_OK){

printf("create tables error: %s\n", errorMsg);

}

ret = sqlite3_exec(db, "insert into Class01 values(1001,'gang',100);",\

callback, "context sqlite...", &errorMsg);

printf("insert: %d, %s\n",ret, errorMsg);

ret = sqlite3_exec(db, "select * from Class01;",\

callback, "context sqlite...", &errorMsg);

sqlite3_close(db);

printf("done\n");

return 0;

}

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: