linux上mysql连接测试_linux下c连接mysql测试

使用的系统是Ubuntu 11.10.数据库是MySQL。

MySQL数据库环境配置

首先需要安装MySQL客户端和服务器,命令行安装方式为:

[cpp]  view plain copy print ?

sudo apt-get install mysql-server mysql-client

然后,要使用C语言编程访问数据库,需要另外安装一个开发包:

[cpp]  view plain copy print ?

sudo apt-get install libmysqlclient15-dev

在MySQL中建立相应数据库

首先以用户rick登录MySQL数据库(用户rick已经被root权限用户赋予了创建数据库等等的权限):

然后创建一个名为foo的数据库:

[cpp]  view plain copy print ?

CREATE DATABASE foo;

然后利用如下SQL语句创建表及插入数据:

[cpp]  view plain copy print ?

CREATE TABLE children(

childno int(11) NOT NULL auto_increment,

fname varchar(30),

age int(11),

PRIMARY KEY (childno)

);

INSERT INTO children(childno,fname,age) VALUES(1,'Jenny',21);

INSERT INTO children(childno,fname,age) VALUES(2,'Andrew',17);

INSERT INTO children(childno,fname,age) VALUES(3,'Gavin',8);

INSERT INTO children(childno,fname,age) VALUES(4,'Duncan',6);

INSERT INTO children(childno,fname,age) VALUES(5,'Emma',4);

INSERT INTO children(childno,fname,age) VALUES(6,'Alex',15);

INSERT INTO children(childno,fname,age) VALUES(7,'Adrian',9);

在MySQL命令行模式中执行方法如下:

MySQL数据库连接测试

然后采用如下C语言进行数据库连接测试connect1.c:

[cpp]  view plain copy print ?

#include

#include

#include "mysql.h"

intmain(intargc,char*argv[])

{

MYSQL *conn_ptr;

conn_ptr = mysql_init(NULL);

if(!conn_ptr)

{

fprintf(stderr,"mysql_init failed\n");

returnEXIT_FAILURE;

}

conn_ptr = mysql_real_connect(conn_ptr,"localhost","rick","rick","foo",0,NULL,0);

if(conn_ptr)

printf("Connection success\n");

else

printf("Connection failed\n");

mysql_close(conn_ptr);

returnEXIT_SUCCESS;

}

执行结果:

注意的是:需要指定include库和库文件的路径名,以及指定链接的库模块mysqlclient。

如果不在开始的时候安装开发包,就会产生如下错误:

执行SQL语句进行数据操作

向数据库表children中插入一行:

[cpp]  view plain copy print ?

#include

#include

#include "mysql.h"

intmain()

{

MYSQL my_connecyion;

intres;

mysql_init(&my_connecyion);

if(mysql_real_connect(&my_connecyion,"localhost","rick","rick","foo",0,NULL,0))

{

printf("Connection success\n");

//执行SQL语句

res = mysql_query(&my_connecyion,"INSERT INTO children(fname,age) VALUES('Ann',3)");

if(!res)

printf("Inserted %lu rows\n",(unsignedlong)mysql_affected_rows(&my_connecyion));

else

fprintf(stderr,"Insert error %d : %s \n",mysql_errno(&my_connecyion),mysql_error(&my_connecyion));

mysql_close(&my_connecyion);

}

else{

fprintf(stderr,"Connection failed\n");

if(mysql_errno(&my_connecyion))

fprintf(stderr,"Connection error %d : %s\n",mysql_errno(&my_connecyion),mysql_error(&my_connecyion));

}

returnEXIT_SUCCESS;

}

运行结果:

在这里特别需要注意的是:

函数mysql_affected_rows返回的是被一个更新操作修改的行数,而不是满足where子句的行数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值