linux c语言操作数据库(连接sqlite数据库)
#include<stdio.h>
#include<sqlite3.h>
int select_callback(void *data,int col_count,char **col_values,char **col_name)
{
//每条记录回调一次该函数,有多少条就回调多少次
int i;
for(i=0;i<col_count;i++)
{
printf("%s=%s\n",col_name[i],col_values[i]==0?"NULL":col_values[i]);
}
return 0;
}
int main(int argc,char **argv)
{
//创建数据库表
const char *SQL1="create table users(id int PRIMARY KEY,name varchar(20),birthday datetime);";
//向数据库插入数据
const char *SQL2="insert into users values(1,'myd','2013-10-9');";
const char *SQL3="insert into users values(2,'myd','2013-10-9');";
//从数据库查询数据
const char *SQL4="select * from users;";
char *ErrMsg=0;
int ret = 0;
//连接数据库
sqlite3 *db =0;
ret=sqlite3_open("./DataBase",&db);
if(ret != SQLITE_OK)
{
fprintf(stderr,"无法打开数据库:%s",sqlite3_errmsg(db));
return 1;
}
printf("数据库连接成功!\n");
//执行建表
ret = sqlite3_exec(db,SQL1,0,0,&ErrMsg);
if(ret != SQLITE_OK)
{
fprintf(stderr,"SQL Error:%s\n",ErrMsg);
sqlite3_free(ErrMsg);
}
//执行插入记录SQL语句
ret = sqlite3_exec(db,SQL2,0,0,&ErrMsg);
if(ret !=SQLITE_OK)
{
printf("插入数据成功\n");
}
ret = sqlite3_exec(db,SQL3,0,0,&ErrMsg);
{
printf("插入数据成功\n");
}
//查询数据表内容
printf("查询数据表内容\n");
sqlite3_exec(db,SQL4,select_callback,0,&ErrMsg);
//关闭数据库
sqlite3_close(db);
db = 0;
printf("数据库关闭成功!\n");
return 0;
}
CFLAGS=-L /usr/local/sqlite-autoconf-3070400/lib -I/usr/local/sqlite-autoconf-307040/include -lsqlite3
all: sqlite.o sqlite
sqlite:sqlite.o
gcc sqlite.o -o sqlite $(CFLAGS)
sqlite.o:sqlite.c
gcc -c sqlite.c $(CFLAGS)
clean:
rm -rf sqlite *.o
栏 目:C代码
下一篇:简介C++编程中的运算符重载
本文标题:linux c语言操作数据库(连接sqlite数据库)
本文地址:http://www.codeinn.net/misctech/11071.html