source code:
/*************************************************************************************
* sqlite.c
* 2011-12-13
* light
* lightwu@hotmail.com
*************************************************************************************/
#include <stdio.h>
#include "sqlite3.h"
int LoadMyInfo(void * para, int n_column, char ** column_value, char ** column_name )
{
// para 是 sqlite3_exec 传入的 void *参数
// 通过 para 参数,可以传入一些特殊的指针,然后强制转换成对应的类型, 再操作这些数据
//n_column 是这一条记录有多少个字段 (即这条记录有多少列)
// char ** column_value 是个关键值,查出来的数据都保存在这里,它实际上是个 1 维数组,每
//一个元素都是一个 char *值,是一个字段内容
//char ** column_name 跟 column_value 是对应的,表示这个字段的字段名称
//这里,不使用 para 参数。忽略它的存在.
int i;
printf("记录包含 %d 个字段\n",n_column);
for( i = 0;i < n_column; i++ )
{
printf("字段名:%s ß>字段值:%s\n",column_name[i],column_value[i] );
}
printf("---------------------\n");
return 0;
}
void main(int argc , char **argv)
{
sqlite3 *db = NULL;
int resault;
char ** errmsg = NULL;
// open datebase
resault = sqlite3_open("/home/light/123/sqlite/db_hello.db",&db);
if( resault != SQLITE_OK )
{
printf("Open failed !\n");
// return -1; // open failed !
}
else
{
printf("Open success !\n");
}
//create a table
resault = sqlite3_exec(db,"create table MyTable_1(ID integer primary key autoincrement, name nvarchar(32))",NULL ,NULL,errmsg );
if(resault = SQLITE_OK)
{
printf("Create table failed :%d ,reason :%s \n", resault,errmsg );
}
resault = sqlite3_exec(db,"insert into MyTable_1(name)values('RUN')",0,0,errmsg);
if(resault != SQLITE_OK)
printf("insert failed ! error is :%d, the failed reason is :%s\n",resault,errmsg );
resault = sqlite3_exec(db,"insert into MyTable_1(name)values('ride a bike')",0,0,errmsg );
if(resault != SQLITE_OK)
printf("insert failed, error is %d,the failed reson is :%s\n",resault,errmsg);
resault = sqlite3_exec(db,"insert into MyTable_1(name)values('by car')",0,0,errmsg );
if(resault != SQLITE_OK)
printf("insert failed, error is %d,the faile reason is :%s\n",resault,errmsg );
// start qurey datebase
resault = sqlite3_exec(db,"select * from MyTable_1",LoadMyInfo,NULL,errmsg);
sqlite3_close(db);
printf("Closed !\n");
// return 0;
}
Makefile:
all : sqlite
sqlite: sqlite.c
gcc -o sqlite sqlite.c -lsqlite3
strip sqlite
clean:
@rm -vf sqlite *.o *~