创建数据库:
简单插入操作:
#include <sqlite3.h> #include <string.h> #include <stdio.h> int main(int argc,char *argv[]){ sqlite3 *db = NULL; sqlite3_stmt * stmt; int ok = sqlite3_open("./demo.db",&db); if (ok == SQLITE_OK){ char * sql = "insert into id_name values(?,?)"; ok = sqlite3_prepare(db,sql,-1,&stmt,0); if (ok != SQLITE_OK){ fprintf(stderr,"error:%s! ",sqlite3_errmsg(db)); return -1; } sqlite3_bind_int(stmt,1,31); sqlite3_bind_text(stmt,2,"hh",strlen("hh"),NULL); ok = sqlite3_step(stmt); if (ok != SQLITE_DONE){ fprintf(stdout,"failure! "); return -1; } } sqlite3_finalize(stmt); sqlite3_close(db); return 0; }
编译:
gcc demo.c -lsqlite3
简单查询操作:
#include <stdio.h> #include <sqlite3.h> int main(int argc,char *argv[]){ sqlite3 *db = NULL; sqlite3_stmt * stmt; int ok = sqlite3_open("/home/liu/CLionProjects/Hi/sqlite3/demo.db",&db); if (ok == SQLITE_OK){ char * sql = "select * from id_name"; ok = sqlite3_prepare(db,sql,-1,&stmt,0); if (ok != SQLITE_OK){ fprintf(stderr,"error:%s ",sqlite3_errmsg(db)); return -1; } printf("sqlite3_column_count(stmt):%d ",sqlite3_column_count(stmt)); //提前知道列数和各列的数据类型! for (;sqlite3_step(stmt) == SQLITE_ROW;) { printf("column0:%d ",sqlite3_column_int(stmt,0)); printf("column1:%s ",sqlite3_column_text(stmt,1)); } } sqlite3_finalize(stmt); sqlite3_close(db); return 0; }
编译:
gcc demo.c -lsqlite3
PS:C API接口函数陆续介绍!