MySQL是Linux系统下广泛使用的开源免费数据库,是Linux应用程序数据存储的首选。许多发布的Linux版本是自带MySQL的,但是也有些发布版本是不带的(比如我现在用的Ubuntu),那就需要手动安装。在Synaptic Packet Management中搜索“mysql”,可以找到“mysql-client"包,点击安装即可。
安装好的MySQL是在命令行下运行的,这对于许多经常在Windows下开发程序,习惯使用图形化工具的人来说是很痛苦的。因此我们需要 安装MySQL图形化管理工具MySQL Administrator和MySQL Query Brower。打开Ubuntu Software Center,输入”mysql"搜索,可以看到这两个工具,点击安装即可。
安装了以上的软件包后,我们可以正常使用MySQL完成数据管理工作,但是很多时候我们需要通过编写程序访问MySQL。此时,在程序中需要加载MySQL驱动头文件,但是默认这些驱动包是没有安装的,因此我们需要在Synaptic Packet Management中找到"libmysqld-dev"包并安装。
用C语言连接MySQL数据库有两个步骤:
1)初始化一个连接句柄结构
2)建立连接
所用到的函数如下:
#include
MYSQL *mysql_init(MYSQL *); // 初始化连接句柄
MYSQL *mysql_real_connect(MYSQL *connection,
constchar*server_host,
constchar*sql_user_name,
constchar*sql_password,
constchar*db_name,
unsigned intport_number,
constchar*unix_socket_name,
unsigned intflags);//建立连接
voidmysql_close(MYSQL *connection);//关闭连接
intmysql_options(MYSQL *connection,enumoption_to_set,constchar*argument);//设置连接选项
option_to_set的值为下列三个值之一:
MySQL_OPT_CONNECT_TIMEOUT //连接超时前的等待秒数
MySQL_OPT_COMPRESS //网络连接中使用压缩机制
MySQL_INIT_COMMAND //每次建立连接后发送的命令
使用上面函数实现MySQL数据库连接的程序如下:
/*
* gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1
*/
#include
#include
#include
intmain()
{
MYSQL *conn_ptr; // 定义连接句柄
conn_ptr = mysql_init(NULL); // 初始化连接句柄
if(!conn_ptr)
{
fprintf(stderr, "mysql_init falied\n");
returnEXIT_FAILURE;
}
// 建立连接
conn_ptr = mysql_real_connect(conn_ptr, "localhost","root","pwd","test", 0, NULL, 0);
if(conn_ptr)
{
printf("Connection success\n");
}
else
{
printf("Connection failed\n");
}
// 关闭连接
mysql_close(conn_ptr);
returnEXIT_SUCCESS;
}
程序编译运行后显示“Connection success"表明程序已经成功与MySQL数据库建立连接,并在程序结束前关闭连接。
上面的程序是在假设没有错误的情况下运行,如果数据库连接过程中出现了错误,我们就需要以下两个函数来处理错误信息:
unsignedintmysql_errno(MYSQL *connection);//返回错误代码(非零值)
char*mysql_error(MYSQL *connection);//返回错误信息
具体使用方法如下:
/*
* gcc -I/usr/include/mysql connect2.c -L/usr/lib/mysql -lmysqlclient -o connect2
*/
#include
#include
#include
intmain(intargc,char*argv[])
{
MYSQL connection;
mysql_init(&connection); //初始化连接
if(mysql_real_connect(&connection,"localhost","root","unknown","test", 0, NULL, 0))//建立连接
{
printf("Connection success\n");
mysql_close(&connection);
}
else//连接失败打印错误信息
{
fprintf(stderr, "Connection failed\n");
if(mysql_errno(&connection))
{
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&connection), mysql_error(&connection));
}
}
returnEXIT_SUCCESS;
}
运行上述程序,如果MySQL的登陆密码不是unknown则打印错误信息(拒绝访问——Access denied)。
程序访问数据库不只是与数据库建立连接,更重要的是通过SQL语句的执行查询或改变数据库中数据。执行SQL语句可以通过下列函数实现。
//执行SQL语句,成功返回0
intmysql_query(MYSQL *connection,constchar*query);
SQL语句分为两类,返回数据的SQL(SELECT)和不返回数据的SQL(UPDATE、DELETE、INSERT)。
1)不返回数据的SQL
// 返回查询受影响的行
my_ulong mysql_affected_rows(MYSQL *connection);
对一段SQL语句执行后可以通过调用此函数查看SQL语句执行后,数据库中数据状态改变的行数,以此判断SQL的执行成功与否。
/*
* gcc -I/usr/include/mysql insert1.c -L/usr/lib/mysql -lmysqlclient -o insert1
*/
#include
#include
#include
intmain(intargc,char*argv[])
{
intres;
MYSQL connection;
mysql_init(&connection);
if(mysql_real_connect(&connection,"localhost","root","pwd","test", 0, NULL, 0))
{
printf("Connection success\n");
res = mysql_query(&connection, "INSERT INTO children(fname, age) VALUES('ann', 3)");
if(!res)
{
printf("Inserted %lu rows\n", (unsignedlong)mysql_affected_rows(&connection));//打印受影响的行数
}
else
{
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(&connection), mysql_error(&connection));
}
mysql_close(&connection);
}
else
{
fprintf(stderr, "Connection failed\n");
if(mysql_errno(&connection))
{
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&connection), mysql_error(&connection));
}
}
returnEXIT_SUCCESS;
}
2)返回数据的SQL
返回数据的SQL是指通过查询语句从数据库中取出满足条件的数据记录。
//一次提取所有数据
MYSQL_RES *mysql_store_result(MYSQL *connection);
//一次提取一行数据
MYSQL_RES *mysql_use_result(MYSQL *connection);
//清除结果集对象
voidmysql_free_result(MYSQL_RES *result);
使用方法如下所示:
#include
#include
#include
MYSQL connection;
MYSQL_RES *sqlres;
MYSQL_ROW sqlrow;
intmain(intargc,char*argv[])
{
intres;
mysql_init(&connection);
if(mysql_real_connect(&connection,"localhost","root","pwd","mysql", 0, NULL, 0))
{
printf("Connection success\n");
res = mysql_query(&connection, "SELECT user, password, host from user");
if(res)
{
printf("SELECT error: %s\n", mysql_error(&connection));
}
else
{
// 一次取全部数据
sqlres = mysql_store_result(&connection);
if(sqlres)
{
printf("Retrieved %lu rows\n", (unsignedlong)mysql_num_rows(sqlres));
while((sqlrow = mysql_fetch_row(sqlres)))
{
printf("Fetched data...\n");
}
if(mysql_errno(&connection))
{
fprintf(stderr, "Retrive error: %s\n", mysql_error(&connection));
}
mysql_free_result(sqlres);
}
// 一次取一行数据
/*sqlres = mysql_use_result(&connection);
if(sqlres)
{
while((sqlrow = mysql_fetch_row(sqlres)))
{
printf("Fetched data...\n");
}
if(mysql_errno(&connection))
{
printf("Retrive error: %s\n", mysql_error(&connection));
}
mysql_free_result(sqlres);
}*/
}
mysql_close(&connection);
}
else
{
fprintf(stderr, "Connection failed\n");
if(mysql_errno(&connection))
{
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&connection), mysql_error(&connection));
}
}
returnEXIT_SUCCESS;
}
一次取全部数据增加了网络负载,但是可以保证数据的完整性。一次取一行数据平衡了网络负载,减小了数据开销,但是增加了时延,因为每次取数据都必须通过网络。
最后一个比较重要的功能是对数据集中的数据进行处理,可能通过列号或者列名来读取数据。
//返回结果集中的字段数目
unsigned intmysql_field_count(MYSQL *connection);
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result);
voiddisplay_row()
{
unsigned intfield_count;
field_count = 0;
while(field_count
{
printf("%s ", sqlrow[field_count]);
field_count++;
}
printf("\n");
}
小结:通过以上分析,可以了解在Linux操作系统环境下如何通过程序建立与MySQL数据的连接,并且通过库函数的调用可以实现对数据库的增删改查操作,在出现错误时,通过函数调用可以返回错误代码,也可以直接返回错误信息。