热门话题

Php 研究室

Linux下mysql的C API简单使用    作者:xieaotian发表于2009-05-22 16:15:21

	   

使用mysql的C API 可以轻松的连接mysql

#include
#include
#include "/usr/include/mysql/mysql.h"

int main(int argc, char** argv)
{
MYSQL *my_conn;
MYSQL_RES *res;
MYSQL_ROW row;
my_conn=mysql_init(NULL);

if(!mysql_real_connect(my_conn,"localhost","root","123","test",0,NULL,0))
{
printf("Connect Error!\n");
exit(1);
}

if(mysql_query(my_conn,"select * from songfei"))
{
printf("Query Error!\n");
exit(1);
}

res=mysql_use_result(my_conn);

printf("The result is:\n");
while((row=mysql_fetch_row(res))!=NULL)
{
printf("%s %s\n",row[0],row[1]);

}

mysql_free_result(res);
mysql_close(my_conn);

return 0;
}



















































































编译和连接程序

  MySQL中有一个特殊的脚本,叫做mysql_config. 它会为你编译MySQL客户端,并连接到MySQL服务器提供有用的信息.你需要使用下面两个选项.

  1. –libs 选项 - 连接MySQL客户端函数库所需要的库和选项.

  $ mysql_config –libs

  输出:

  -L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto

  2. –cflags 选项 - 使用必要的include文件的选项等等.

  $ mysql_config –cflags

  输出:

  -I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing

  你需要将上面两个选项加入到对源文件的编译命令中. 所以,要编译上面的程序,要使用下面的命令:

  $ gcc -o output-file $(mysql_config –cflags) mysql_test.c $(mysql_config –libs)

回复主题
Copyright © 2008-2010 版权所属:中国Python联盟 www.okpython.com
京ICP备08012290号 村长QQ:81356625 E-mail:xieaotian@163.com