Linux下C 訪問MySQL《一》

2021-08-25 21:08:03 字數 2897 閱讀 1432

/*

配置開發環境

首先需要編譯、安裝mysql,安裝完成後,將mysql目錄中的lib目錄新增到環境變數中。

新建c/c++工程,把$mysql_root/include新增到編譯環境的包含路徑下面。在編譯選項中,增加$mysql_root/lib目錄。在link選項中增加-lmysqlclient(已經把lib目錄增加到系統環境變數中),或者直接引用libmysqlclient.so檔案。

*/#ifndef mysqlmanager_h_   

#define mysqlmanager_h_  

#include "../common/checkstringtools.h"  

#include

#include

#include

#include

#include

using

namespace

std;  

class

mysqlmanager

;#endif

/* mysqlmanager_h_ */

#include "mysqlmanager.h"  

mysqlmanager

::mysqlmanager(

string

hosts

,string

username

,string

password

,string

dbname

,unsigned

intport)   

mysqlmanager

::~mysqlmanager()   

void

mysqlmanager

::setdbname(

string

dbname)   

else

}void

mysqlmanager

::sethosts(

string

hosts)   

else

}void

mysqlmanager

::setpassword(

string

password)   

else

}void

mysqlmanager

::setport(

unsigned

intport)   

else

}void

mysqlmanager

::setusername(

string

username)   

else

}void

mysqlmanager

::initconnection()   

mysql_init(

&mysqlclient);

//    初始化相關物件   

if (

!mysql_real_connect(

&mysqlclient

,hosts

,username

,password

,dbname

,defaultport

,null

,0) )   

isconnected

=true;

//    修改連線標識   

}bool

mysqlmanager

::runsqlcommand(

string

sql)   

if (

sql.empty() )   

mysql_res

*res;   

mysql_row

row;  

unsigned

inti,j

=0;  

stringtools

stringtools;   

sql=stringtools

.filterstring(

sql);   i

=mysql_real_query(

&mysqlclient

,sql

.c_str

(),(

unsigned

int)

strlen(

sql.c_str()));

//    執行查詢   

if (

i )   

res=mysql_store_result(

&mysqlclient);   

vector

<

string

>

objectvalue;   

while( (

row=mysql_fetch_row(

res)) )   

this

->

resultlist

.push_back(

objectvalue);    }

mysql_free_result(

res);        

//free result after you get the result  

return

true;    }

vector

<

vector

<

string

>

>

mysqlmanager

::getresult()   

void

mysqlmanager

::destroyconnection()   

bool

mysqlmanager

::getconnectionstatus()   

linux下遠端訪問Mysql

mysql的root賬戶,我在連線時通常用的是localhost或127.0.0.1,公司的測試伺服器上的mysql也是localhost所以我想訪問無法訪問,測試暫停.解決方法如下 1,修改表,登入mysql資料庫,切換到mysql資料庫,使用sql語句檢視 select host,user fr...

linux下c程式訪問mysql小例子

1 c程式訪問mysql include include include define db server 192.168.10.33 define db name ddource define db user oldboy define db pwd oldboy123 static mysql ...

linux下C 訪問mysql資料庫

在這個程式中,比上一次的要完善一些,實現了通過c 對資料表進行新增,修改,插入,刪除的功能。標頭檔案 mydb.h ifndef mydb class define mydb class include include include class mydb endifmydb.cpp include...