废话不多说, 直接上代码,我也是根据refman 文档编写的,在网上找了一圈,没找到相应的访问代码。
第一步: 首先要安装MYSQL相关开发包,主要安装如下两个包就能访问MySQL库了,linux下安装比较简单,直接执行如下命令即可:
rpm -ivh
mysql-libs-5.1.61-4.el6.x86_64
rpm -ivh
mysql-devel-5.1.61-4.el6.x86_64
第二步:编写访问mysql的C代码, 假设要访问 192.169.33.145 机器上的test 数据库的ttt表, 用户名 , scott, tiger , C代码文件名称为 mqtst.c
-
#include<stdio.h>
-
#include<mysql/mysql.h>
-
#include<string.h>
-
#define LEN_NAME 30
-
int main(int argc ,char** argv)
-
{
-
MYSQL* mysql ;
-
MYSQL_STMT* stmt;
-
MYSQL_BIND bind[2];
-
int i = 0 ;
-
char sname[3][LEN_NAME+1]={"zhangsan","lisi","wangwu"};
-
int tid[3] = {0,1,2} ;
-
unsigned long ulname ;
-
char rstmt[] = "insert into ttt(c0,c1)values(?,?)";
-
-
mysql = mysql_init(NULL);
-
if(mysql == NULL)
-
{
-
return -1 ;
-
}
-
if(! mysql_real_connect(mysql,"192.169.33.145","scott","tiger","test",0,0,0))
-
{
-
printf("connect database error [%d,%s]\n",mysql_errno(mysql),mysql_error(mysql));
-
mysql_close(mysql);
-
return -1;
-
}
-
//
-
stmt = mysql_stmt_init(mysql);
-
if(!stmt)
-
{
-
printf("init stmt error %s\n",mysql_error(mysql));
-
mysql_close(mysql);
-
return -1 ;
-
}
-
if( mysql_stmt_prepare(stmt,rstmt,strlen(rstmt)))
-
{
-
printf("mysql stmt prepare error (%d,%s)\n",mysql_errno(mysql),mysql_error(mysql));
-
mysql_stmt_close(stmt);
-
mysql_close(mysql);
-
return -1 ;
-
}
-
memset(bind,0,sizeof(bind));
-
for(i = 0 ; i < 3; ++i)
-
{
-
bind[0].buffer_type = MYSQL_TYPE_LONG ;
-
bind[0].buffer = (char*)& tid[i];
-
bind[0].is_null = 0 ;
-
-
bind[1].buffer_type = MYSQL_TYPE_STRING ;
-
bind[1].buffer = (char*)sname[i];
-
bind[1].buffer_length = LEN_NAME ;
-
bind[1].length = &ulname;
-
bind[1].is_null = 0 ;
-
ulname = strlen(sname[i]);
-
-
if(mysql_stmt_bind_param(stmt,bind))
-
{
-
printf("mysql_stmt_bind_param error (%d,%s)\n",mysql_stmt_errno(stmt),mysql_stmt_error(stmt));
-
mysql_stmt_close(stmt);
-
mysql_close(mysql);
-
return -1 ;
-
}
-
if(mysql_stmt_execute(stmt))
-
{
-
printf("mysql_stmt_execute error: %s\n",mysql_stmt_error(stmt));
-
mysql_stmt_close(stmt);
-
mysql_close(mysql);
-
return -1 ;
-
}
-
printf("affect rows = %ld \n",mysql_affected_rows(mysql));
-
}
-
mysql_stmt_close(stmt);
-
mysql_close(mysql);
-
return 0 ;
-
}
第三步,编译代码,前提机器一定要安装编译器cc ,执行如下命令
-bash-4.1$ cc -o mqtst mqtst.c -lmysqlclient
-bash-4.1$
第四步,执行./mqtst
第五步,检查是否已经插入数据
mysql> select * from ttt ;
+----+----------+
| c0 | c1 |
+----+----------+
| 0 | zhangsan |
| 1 | lisi |
| 2 | wangwu |
+----+----------+
3 rows in set
mysql>
阅读(5417) | 评论(0) | 转发(0) |