这个问题几乎困扰了我一天,终于得到解决。
第一首先下载mysql-server、mysql-client、mysql-connector,把mysql-connector解压之后,把头文件考到/usr/include下面,把库文件拷到/usr/lib下面。
然后编写一个C++程序,我的例子如下:
#ifndef __MYSQL_JOB_H
#define __MYSQL_JOB_H
//#ifdef _cplusplus
//extern "C"{
//#endif
//#include "/usr/include/mysql/mysql.h"
//#include "/usr/include/mysql/errmsg.h"
//#include <mysql/my_pthread.h>
#include <mysql/mysql.h>
#include <mysql/errmsg.h>
#include <iostream>
#include <string>
using namespace std;
class MysqlJob{
public:
MysqlJob(char* usr, char* pwd, char* host){
strUsr = usr;
strPassword = pwd;
strHost = host;
mysql_init(&mySQL);
mysqlRet=NULL;
isConnected = false;
}
~MysqlJob(){
CloseMySql();
}
void inline Sql_SetUsrName(char* name){
strUsr = name;
}
void inline Sql_SetDatabaseName(char* DatabaseName){
strDatabaseName = DatabaseName;
}
void inline Sql_SetPassword(char* pwd){
strPassword = pwd;
}void inline Sql_SetHost(char* host){
strHost = host;
}
int Sql_Connect();
void CloseMySql();
int inline Sql_isConnected()
{
return isConnected;
}
protected:
private:
MYSQL mySQL;
MYSQL_RES *mysqlRet;
MYSQL_ROW mysqlRow;
string strUsr;
string strDatabaseName;
string strPassword;
string strHost;
bool isConnected;
};
//#ifdef _cplusplus
//}
//#endif
#endif
#include "mysql_job.h"
void MysqlJob::CloseMySql()
{
mysql_close(&mySQL);
}
int MysqlJob::Sql_Connect()
{
if(mysql_real_connect(&mySQL, strHost.c_str(), strUsr.c_str(), strPassword.c_str(),strDatabaseName.c_str(), 0, NULL, 0)==NULL){
switch(mysql_errno(&mySQL)){
case CR_UNKNOWN_HOST:
cout<<mysql_error(&mySQL);
break;
case CR_VERSION_ERROR:
cout<<mysql_error(&mySQL);
break;
case CR_OUT_OF_MEMORY:
cout<<mysql_error(&mySQL);
break;
case CR_IPSOCK_ERROR:
cout<<mysql_error(&mySQL);
break;
case CR_SOCKET_CREATE_ERROR:
cout<<mysql_error(&mySQL);
break;
default:
cout<<mysql_error(&mySQL);
break;
}
return -1;
}
isConnected = true;
return 1;
}
#define TEST
#ifdef TEST
int main()
{
MysqlJob jobcon("root", "13349", "localhost");
if( jobcon.Sql_Connect() < 0){
cout<<"connect error!/n";
return 1;
}else{
cout<<"connect successed!/n";
}
jobcon.CloseMySql();
}
#endif
然后编译: g++ mysql_job.h mysql_job.cpp -o mysql_job -lmysql
因为程序头文件和库的路径都是/usr/include 和/usr/lib下面,所以我们不需要指定头文件和库文件的路径,编译之后,我们可以执行一下,发现有一个错误:Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)connect error!
原因是我在装mysql的时候,从/usr/share/mysql拷贝了一个.cnf文件到/etc/my.cnf了,指定了数据库存储路径,从而指定了sock的路径
:/home/data/mysql/mysql.sock,因此需要在mysql_real_connect函数里面需要指定unix_sock一项为“/home/data/mysql/mysql.sock”,否则如果指定为NULL的话则默认为“/tmp/mysql.sock”了。至此,成功连接!