---
title: "Linux C语言连接MySQL 增删改查操作"
author: "asyty"
date: "2012-03-09T09:09:19Z"
tags: ["C语言", "Linux", "MySQL", "函数未定义", "找不到头文件"]
categories: ["开源软件"]
slug: "linux-c-mysql"
draft: false
lastmod: "2012-03-11T22:01:34Z"
id: 1447092
url: "https://asyty.iteye.com/blog/1447092"
---

Linux下想要测试mysql和memcached的性能，因为是服务器只能通过终端连接，所以考虑用C语言写测试代码。于是研究了把C怎么连接MySQL以及增删改查的代码。安装mysql-client或者编译源码安装mysql后，会有支持C语言写客户端的头文件和库文件，但是目录可能不一样，mysql源码安装见 [**http://asyty.iteye.com/blog/1442503**](/blog/1442503)

从网上找了类似的代码改改后如下

 

连接数据库

 

```
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
int main() {
	MYSQL *conn_ptr;

	conn_ptr = mysql_init(NULL);
	if (!conn_ptr) {
		printf("mysql_init failed\n");
		return EXIT_FAILURE;
	}
	conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "123456", "test", 0, NULL, 0);
	//root 为用户名 123456为密码 test为要连接的database

	if (conn_ptr) {
		printf("Connection success\n");
	} else {
		printf("Connection failed\n");
	}
	mysql_close(conn_ptr);
	return EXIT_SUCCESS;
}
```

 

 通过gcc编译（我的mysql源码安装目录为 /usr/local/mysql）

 

gcc -o connect -g connect.c  -I /usr/local/mysql/include/ -L /usr/local/mysql/lib/ -l mysqlclient

 

参数说明：-I（大写的i） 表示要连接的头文件目录，因为使用了&lt;mysql.h&gt; ，-L表示要连接的库文件目录 -l（小写的L） 表示要连接的具体的库名称，在/usr/local/mysql/lib/ 下，有叫做libmysqlclient.so的库，指定具体的库的名字时，默认去掉头尾的lib和.so直接使用中间的mysqlclient

如果不用-I -L ，可能导致找不到头文件 或者 函数未定义的错误

 

如果出现错误error while loading shared libraries，那是因为.so没有被系统载入，解决办法如下

vi /etc/ld.so.conf // 打开ld.so.conf文件，增加.so文件的路径，比如/usr/local/mysql/lib/

ldconfig //重新加载.so文件

 

 

查询代码  

```
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
int main() {
	MYSQL *conn_ptr;
	MYSQL_RES *res_ptr;
  	MYSQL_ROW sqlrow;
	MYSQL_FIELD *fd;
	int res, i, j;

	conn_ptr = mysql_init(NULL);
	if (!conn_ptr) {
		return EXIT_FAILURE;
	}
	conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "123456", "test", 0, NULL, 0);
	if (conn_ptr) {
		res = mysql_query(conn_ptr, "select name,age from user"); //查询语句
		if (res) {       
			printf("SELECT error:%s\n",mysql_error(conn_ptr));   
		} else {      
			res_ptr = mysql_store_result(conn_ptr);				//取出结果集
			if(res_ptr) {             
				printf("%lu Rows\n",(unsigned long)mysql_num_rows(res_ptr)); 
				j = mysql_num_fields(res_ptr);        
				while((sqlrow = mysql_fetch_row(res_ptr)))  {	//依次取出记录
					for(i = 0; i < j; i++)       
						printf("%s\t", sqlrow[i]); 				//输出
					printf("\n");        
				}            
				if (mysql_errno(conn_ptr)) {                    
					fprintf(stderr,"Retrive error:s\n",mysql_error(conn_ptr));             
				}      
			}      
			mysql_free_result(res_ptr);      
		}
	} else {
		printf("Connection failed\n");
	}
	mysql_close(conn_ptr);
	return EXIT_SUCCESS;
}
```

 

 

插入更新及删除 

 

```
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
int main() {
	MYSQL *conn_ptr;
	int res;

	conn_ptr = mysql_init(NULL);
	if (!conn_ptr) {
		printf("mysql_init failed\n");
		return EXIT_FAILURE;
	}
	conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "123456", "test", 0, NULL, 0);
	if (conn_ptr) {
		res = mysql_query(conn_ptr, "insert into user values(null,'Ann',5)"); 	//可以把insert语句替换成delete或者update语句，都一样的
//		res = mysql_query(conn_ptr, "delete from user where name = 'Ann' and age < 10");
		if (!res) {		//输出受影响的行数
			printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn_ptr));	
		}  else {		//打印出错误代码及详细信息
			fprintf(stderr, "Insert error %d: %sn",mysql_errno(conn_ptr),mysql_error(conn_ptr));
		}
	} else {
		printf("Connection failed\n");
	}
	mysql_close(conn_ptr);
	return EXIT_SUCCESS;
}
```

 

 

转载请注明源  [**http://asyty.iteye.com/blog/1447092**](/blog/1447092)