`
yuanyu5237
  • 浏览: 159436 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

linux下C语言连接mysql数据库

阅读更多

我用的是ubuntu10.10,   mysql是使用sudo命令安装;

 

在linux下使用C语言连接mysql数据库,

首先执行命令:

sudo apt-get install libmysqlclient-dev

然后,执行下面的命令: 

mysql_config --libs

mysql_config --cflags

然后,写一个测试程序showtables.c,用来查看mysql数据库中某个库里所有的表,这里我们默认查看系统数据库mysql中的所有表:

 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mysql.h>

int main() {
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *server = "localhost";
	char *user = "root";
	char *password = "xxxxxx";    /*  password */
	char *database = "mysql";
	conn = mysql_init(NULL);
	/* Connect to database */
	if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0)) 
	{
		fprintf(stderr, "%sn", mysql_error(conn));
		exit(1);
	}
	/* send SQL query */
	if (mysql_query(conn, "show tables"))
	{
		fprintf(stderr, "%sn", mysql_error(conn));
		exit(1);
	}
	res = mysql_use_result(conn);
	/* output table name */
	//printf("MySQL Tables in mysql database: \n");
	while ((row = mysql_fetch_row(res)) != NULL)
		printf("%s\n", row[0]);
	/* close connection */
	mysql_free_result(res);
	mysql_close(conn);
}

 然后编译该程序,使用命令:

gcc -o showtables $(mysql_config --cflags) showtables.c $(mysql_config --libs)

运行结果: ./showtables

 

运行结果 写道
MySQL Tables in mysql database:
columns_priv
db
event
func
general_log
help_category
help_keyword
help_relation
help_topic
host
ndb_binlog_index
plugin
proc
procs_priv
servers
slow_log
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user

 

 

在这里,我不过多解释命令和程序的意思,因为我自己也刚开始学这个,所以这个程序的目的就是只要能运行成功,达到程序的目的即可。

 

我主要参考的两篇文章:

http://www.linuxdiyf.com/viewarticle.php?id=74787

 

http://www.cppblog.com/xuejzt/archive/2009/05/23/85540.aspx

 

记录两个链接:

http://www.cppblog.com/xuejzt/archive/2009/05/23/85540.aspx

 

http://auautitikkk.blog.163.com/blog/static/3378223420104268292011/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics