老版本的SQLite编程接口很简单,只有5个接口。随着新功能的增加,新版本的SQLite有185个编程接口。 但是不用担心,核心API还是很容易理解的。
1. 先来介绍核心对象和接口
(1) 数据库连接对象 sqlite3
(2) 执行语句对象 sqlite3_stmt
sqlite3_stmt不是必须的, 因为接口sqlite3_exec或sqlite3_get_table提供了直接访问数据库的功能,但是理解sqlite3_stmt对理解sqlite是如何工作的很有帮助。
请看一下SQLite核心接口, 这些名字只是概念上的, 真正的名字可能不一样,或者可能有多个版本。比如sqlite3_open() 有sqlite3_open16() and sqlite3_open_v2().
* sqlite3_open(), 创建数据库连接,返回sqlite3_db * sqlite3_prepare(),创建sqlite3_stmt对象 * sqlite3_step(), 前进到下一行 * sqlite3_column(), 取得某一列的值,有很多别名 * sqlite3_finalize(), 销毁sqlite3_stmt对象 * sqlite3_close(), 关闭数据库连接sqlite3_db,释放资源。
sqlite3_column()有以下:
* sqlite3_column_blob() * sqlite3_column_bytes() * sqlite3_column_bytes16() * sqlite3_column_count() * sqlite3_column_double() * sqlite3_column_int() * sqlite3_column_int64() * sqlite3_column_text() * sqlite3_column_text16() * sqlite3_column_type() * sqlite3_column_value()
另外两个很有用的接口
sqlite3_reset(), 重新执行已经存在的sqlite3_stmt sqlite3_bind(),使一个prepared statement 执行多次时,绑定到不同的数据源, 比如INSERT多行数据
2. 扩展SQLite的API
* sqlite3_create_collation() * sqlite3_create_function() * sqlite3_create_module() * sqlite3_aggregate_context() * sqlite3_result() * sqlite3_user_data() * sqlite3_value() 跟多详细做法请看date.c and func.c
本文只介绍了部分核心API,其他API请看SQLite API Reference
3. 来个例子
1 struct { 2 char*name; char*occ; 3 } values[]={ 4 "Li Lei",CEOHan MeimeiCPO 5 LilyCOOLucyCFO 6 }; 7 #define LEN(x) sizeof(x)/sizeof(x[0]) 8 void my_first_sqlite3_func() 9 { 10 int i; 11 sqlite3 *db; 12 sqlite3_stmt *stmt; 13 char name[16],occ[16]; 14 char*sql_drop=drop table if exists people;"; 15 char*sql_create=create table people (name,occupation);16 char*sql_insert=insert into people values (?,?);17 char*sql_select=select * from people;18 19 sqlite3_open(D:/first_0704.db&db); 20 sqlite3_prepare(db,sql_drop,strlen(sql_drop),&stmt,NULL); 21 sqlite3_step(stmt); 22 23 sqlite3_prepare(db,sql_create,strlen(sql_create),128)">24 sqlite3_step(stmt); 25 26 sqlite3_prepare(db,sql_insert,strlen(sql_insert),128)">27 for(i=0;i<LEN(values);i++) 28 { 29 //printf("INSERT name=%s,occ=%sn",values[i].name,values[i].occ); 30 sqlite3_bind_text(stmt,128)">1,strlen(values[i].name),SQLITE_STATIC); 31 sqlite3_bind_text(stmt,128)">2,values[i].occ,strlen(values[i].occ),128)">32 sqlite3_step(stmt); 33 sqlite3_reset(stmt); 34 } 35 36 sqlite3_prepare(db,sql_select,strlen(sql_select),128)">37 i=0; 38 while(SQLITE_DONE !=sqlite3_step(stmt)) 39 { 40 printf(Result[%d]: name=%s,occ=%sn41 i++,128)">42 sqlite3_column_text(stmt,128)">0),128)">43 sqlite3_column_text(stmt,128)">1)); 44 } 45 46 sqlite3_finalize(stmt); 47 sqlite3_close(db); 48 }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|