C++ 操作Mysql
1. 安装mysql
sudo apt install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqld-dev
2. 编译指令
先使用mysql_config --libs 检查mysql链接的类库
ljn@ljn-virtual-machine:~/文档/demo$ mysql_config --libs
-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl
在makefile中新增链接指令
mydb:main.cc
g++ main.cc -o mydb -L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl
3. 数据库操作类
class Db
{
public:
Db(const string &host, const string &username, const string &password, const string &db)
{
conn = mysql_init(NULL);
if (conn == NULL)
goto error;
conn = mysql_real_connect(conn, host.c_str(),
username.c_str(), password.c_str(), db.c_str(), 0, NULL, 0);
if (conn == NULL)
goto error;
return;
error:
cout << "error" << endl;
exit(-1);
}
~Db()
{
if (conn != NULL)
mysql_close(conn);
};
void query(const string &sql)
{
MYSQL_RES *res = NULL;
MYSQL_ROW row = NULL;
int ret = mysql_query(conn, sql.c_str());
if (ret == -1){
goto error;
}
res = mysql_store_result(conn);
printf("number of dataline returned: %d\n", mysql_affected_rows(conn));
for(int i = 0;i<res->field_count;i++)
printf("%s ",res->fields[i].name);
printf("\n");
while(row =mysql_fetch_row(res)){
for(int i = 0;i<res->field_count;i++)
cout<<row[i]<<" ";
cout<<endl;
}
return;
error:
cout << "error" << endl;
exit(-1);
}
private:
MYSQL *conn;
};
|