红联Linux门户
Linux帮助

Ubuntu下用C连接MySQL数据库

发布时间:2014-11-11 16:20:34来源:linux网站作者:fjssharpsword

为了用C连接数据库,上网查了这么多东西都没连接成功,纠结。到最后发现其实也就是简单两步就解决的问题。

先放出示例代码,这个网上随便找一个就是了,旨在测试现行的MYSQL数据库能不能于C连接上。


#include
#include
#include
#include “mysql/mysql.h” //mysql.h目录
using namespace std;
string host=”localhost”;
string user=”root”;
string pwd=“”; //这里加上你数据库的密码
string dbname=”test”; //数据库名称
string sql=”"; //数据库语句
unsigned int port=3309; //端口
int status;
int main(){
MYSQL *mysql;
mysql=mysql_init(0);
MYSQL_RES *result;
MYSQL_ROW row;
if(mysql_real_connect(mysql,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),port,NULL,CLIENT_FOUND_ROWS)==NULL){
cout << "connect failure!" << endl;
return EXIT_FAILURE;
}else{
cout << "connect success!" << endl;
}
mysql_set_character_set(mysql,"gbk");
status=mysql_query(mysql,sql.c_str());
if(status !=0 ){
cout << "query failure!" << endl;
}
cout << "the status is :" << status << endl;
result=mysql_store_result(mysql);
while(row=mysql_fetch_row(result)){
cout << row[1] <<"|"<< row[2] << endl;

}
mysql_free_result(result);
mysql_close(mysql);

}


1.一开始编译都不用编译,我找遍了整个硬盘找不到mysql.h,网上什么乱七八糟的方法,对我来说都是白扯,我就是少装了libmysqlclient15-dev这个软件包,执行

sudo apt-get install libmysqlclient15-dev,第一步解决,mysql.h文件在usr/include/mysql目录下。


2.好了,现在开始编译,8个错误,mysql_开头的所有函数都没有定义,undefined reference to `mysql_init()......等等等,这个可是折腾死我我了,关于mysql的什么开发库我都已经装了,mysqlclient也已经装了,为什么会找不到这些函数呢?我甚至上国外的乱等折腾了很久,啥都没整出来,其实用gcc -o output-file $(mysql_config –cflags) main.cpp $(mysql_config –libs)来编译源文件的想法是对的,但是我就是找不到库的目录,纠结...又是将近全盘搜索,总算找到libmysqlclient.so文件,接下来要做的就是让codeblocks知道这个文件的目录就是了,打开settings -> compiler and debugger,点linker settings,添加libmysqlclient.so文件的目录。


好了,就这么两步,运行一下,connect successt,就这两步。