插入:insert
刚刚我们知道了怎么调用 sqlite3 的C/C++的API函数接口,下面我们看看怎么在C语言中向数据库插入数据。
好的,我们现编辑一段c代码,取名为 insert.c
// name: insert.c
// This prog is used to test C/C++ API for sqlite3 .It is very
simple,ha !
// Author : zieckey All rights reserved.
// data : 2006/11/18
#include
#include
#include "sqlite3.h"
#define _DEBUG_
int main( void )
{
sqlite3 *db=NULL;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("zieckey.db", &db);
//打开指定的数据库文件,如果不存在将创建一个同名的数据库文件
if( rc )
{
fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
else printf("You have opened a sqlite3 database named zieckey.db
successfully!
Congratulations! Have fun ! ^-^
");
//创建一个表,如果该表存在,则不创建,并给出提示信息,存储在 zErrMsg 中
char *sql = " CREATE TABLE SensorData(
ID INTEGER PRIMARY KEY,
SensorID INTEGER,
SiteNum INTEGER,
Time VARCHAR(12),
SensorParameter REAL
);" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
#ifdef _DEBUG_
printf("%s
",zErrMsg);
#endif
//插入数据
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 ,
'200605011206', 18.9 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 ,
'200605011306', 16.4 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sqlite3_close(db); //关闭数据库
return 0;
}
好的,将上述代码写入一个文件,并将其命名为 insert.c 。
解释:
sqlite3_exec的函数原型说明如下:
int sqlite3_exec(
sqlite3*,
const char *sql,
sqlite_callback,
void *,
char **errms
g
);
编译:
[root@localhost temp]# gcc insert.c -lsqlite3
-L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
insert.c:28:21: warning: multi-line string literals are
deprecated
[root@localhost temp]#
执行
[root@localhost temp]# ./a.out
./a.out: error while loading shared libraries:
libsqlite3.so.0: cannot open shared object file: No such file or
directory
[root@localhost temp]#
同样的情况,如上文处理方法:
[root@localhost temp]# export
LD_LIBRARY_PATH=/usr/local/sqlite3/lib:$LD_LIBRARY_PATH
[root@localhost temp]# ./a.out
You have opened a sqlite3 database named zieckey.db
successfully!
Congratulations! Have fun ! ^-^
(null)
(null)
(null)
[root@localhost temp]#
运行成功了,好了,现在我们来看看是否插入了数据
[root@localhost temp]# /usr/local/sqlite3/bin/sqlite3
zieckey.db
SQLite version 3.3.8
Enter ".help" for instructions
sqlite> select * from SensorData;
1|1|1|200605011206|18.9
2|1|1|200605011306|16.4
sqlite>
哈哈,已经插入进去了,不是吗?
很简单是不?