#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sqlite3.h>
int main( int argc, char **argv )
{
sqlite3 *db;
sqlite3_stmt * stmt;
const char *zTail;
//打开数据库
int r = sqlite3_open("mysqlite.db",&db);
if(r){
printf("%s",sqlite3_errmsg(db));
}
else
printf("open db sccess!\n");
//创建Table
//sqlite3_prepare()将SQL语句编译为sqlite内部一个结构体(sqlite3_stmt),
//该结构体中包含了将要执行的SQL语句的信息
//第四个参数用来指向输入参数中下一个需要编译的SQL语句存放的 SQLite statement 对象的指针
sqlite3_prepare(db,
"CREATE TABLE players ( ID INTEGER PRIMARY KEY, name TEXT, age INTEGER);",
-1,&stmt,&zTail);
printf("prepared has done\n");
//调用sqlite3_step(),此时SQL语句才真正执行,执行成功,返回SQLITE_DONE或SQLITE_ROW.
//每次调用sqlite3_step(),只返回一行数据,使用sqlite3_column_XXX()函数来取出这些数据
//要取出全部的数据,则需要反复调用sqlite3_step()
sqlite3_step(stmt);
//调用sqlite3_finalize(),释放stmt占用的内存,该内存是在sqlite3_prepare()时分配的
//如果SQL语句要重复使用,可以调用sqlite3_reset()来清除已经绑定的参数
sqlite3_finalize(stmt);
printf("create table success!\n");
//插入数据
sqlite3_prepare(db,
"INSERT INTO players (name,age) VALUES(?,?);",
-1,&stmt,&zTail);
char str[] = "Kevin";
int n = 23;
//sqlite3_bind_xxx的第四个参数为负,则字符串长度由第一个0终止的位数决定
//SQLITE_STATIC表示命令执行完后的信息为static类型,不能被改动,而且不需要被free
sqlite3_bind_text(stmt,1,str,-1,SQLITE_STATIC);
sqlite3_bind_int(stmt,2,n);
r = sqlite3_step(stmt);
if( r!=SQLITE_DONE){
printf("%s",sqlite3_errmsg(db));
}
//清除已经绑定的参数
sqlite3_reset(stmt);
//插入第二个数据
char str2[] = "Jack";
int n2 = 16;
sqlite3_bind_text(stmt,1,str2,-1,SQLITE_STATIC);
sqlite3_bind_int(stmt,2,n2);
r = sqlite3_step(stmt);
if( r!=SQLITE_DONE){
printf("%s",sqlite3_errmsg(db));
}
sqlite3_finalize(stmt); //释放stmt所占的内存
//查询所有数据
sqlite3_prepare(db,
"SELECT ID, name, age FROM players ORDER BY age",
-1,&stmt,&zTail);
r = sqlite3_step(stmt);
int number;
int id;
const unsigned char * name;
while( r == SQLITE_ROW ){
id = sqlite3_column_int( stmt, 0 );
name = sqlite3_column_text( stmt,1 );
number = sqlite3_column_int( stmt, 2 );
printf("ID: %d Name: %s Age: %d \n",id,name,number);
sleep(1);
r = sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
//关闭数据库
sqlite3_close(db);
return 0;
}
编译运行:
$ gcc sqlite.c –o sqlite –lsqlite3
$ ./sqlite