2.通过调用mysql_init()初始化连接处理程序,并通过调用mysql_real_connect()连接到服务器。
3.发出SQL语句并处理其结果。(在下面的讨论中,详细介绍了使用它的方法)。
4.通过调用mysql_close(),关闭与MySQL服务器的连接。
5.通过调用mysql_library_end(),结束MySQL库的使用。
下面我们看看怎么在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 <stdio.h>
#include <stdlib.h>
#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>
帮你一下吧,我只能粗写,你自己详细参考一下函数库,下面localhost,是数据库服务器的地址,username,password分别为访问数据库所需要的用户名和密码,database是数据库的名称,请你参考MYSQL结构体以获取更加详细的参数信息
#include <stdlib.h>
#include<stdio.h>
#include "mysql.h"
int main(int argc,char**argv){
MYSQL *conn_ptr
conn_ptr=mysql_init(NULL)
if(!conn_ptr){
fprintf(stderr,"mysql_init failed\n")
return EXIT_FAILURE
}
conn_ptr=mysql_real_connect(conn_ptr,"localhost","username","password","database",0,NULL,0)
if(conn_ptr){
printf("Connection success\n")
}else{
printf("Connection failed\n")
}
mysql_close(conn_ptr)
return EXIT_SUCCESS
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)