积累知识,方便自己
分类: C/C++
2011-11-24 14:05:04
实例代码(test_sqlite.h,test_main.c)
test_sqlite.h:
#include
sqlite3 *open_sqlite_db(char *dbname);
void create_sqlite_table(sqlite3 *db,char *tablename,char *SQL);
void insert_sqlite_table(sqlite3 *db,char *tablename,char *str);
void query_sqlite_table(sqlite3 *db,char *tablename);
void close_sqlite_db(sqlite3 *db);
sqlite3 *open_sqlite_db(char *dbname)
{
int rc;
sqlite3 *db=NULL;
rc=sqlite3_open(dbname,&db);
return db;
}
void create_sqlite_table(sqlite3 *db,char *tablename,char *SQL)
{
char sql[1024];
char *errmsg;
sprintf(sql,"CREATE TABLE %s(%s);",tablename,SQL);
sqlite3_exec(db,sql,0,0,&errmsg);
}
void insert_sqlite_table(sqlite3 *db,char *tablename,char *str)
{
char sql[1024];
char *errmsg;
sprintf(sql,"INSERT INTO %s VALUES(null,%s);",tablename,str);
sqlite3_exec(db,sql,0,0,&errmsg);
}
/*查询数据库db中tablename表中的内容*/
void query_sqlite_table(sqlite3 *db,char *tablename)
{
char sql[1024];
int nrow = 0, ncolumn = 0;
char *errmsg;
char **azResult;
int i=0,j=0;
sprintf(sql,"SELECT * FROM %s",tablename);
sqlite3_get_table(db,sql,&azResult, &nrow , &ncolumn , &errmsg );
printf("row:%d column=%d\n",nrow,ncolumn);
for( i=1 ; i<=nrow; i++ ){
printf("the %d row is ",i);
for(j=i*ncolumn;j<(i+1)*ncolumn;j++)
printf( "%s ",azResult[j] );
printf("\n");
}
sqlite3_free_table(azResult);
}
void close_sqlite_db(sqlite3 *db)
{
sqlite3_close(db);
}
test_main.c:
#include
#include “test_sqlite.h”
int main(void)
{
sqlite3 *db=NULL;
char dbname[]=”test”;
char tablename[]=”20115050”;
char str[]=”Bob”;
char create_sql[]=”id INTEGER PRIMARY KEY,name VARCHAR(20)”;
db=open_sqlite_db(dbname);
create_sqlite_table(db,tablename,create_sql);
insert_sqlite_table(db,tablename,str);
query_sqlite_table(db,tablename);
close_sqlite_db(db);
return 0;
}
编译:gcc –o test test_main.c –lsqlite3