linux下C++连接mysql查询数据

windows下使用C++连接mysql相对繁琐,这里直接在linux下通过C++连接mysql,执行查询操作。linux下连接mysql,需要本机有libmysqlclient库文件,最直接的方式就是安装mysql,因为本身就需要一个mysql服务器。

linux下安装mysql,这里就不说了,默认,我们会安装上mariadb,如果需要安装mysql社区版本,我们需要下载对应的repo文件,然后通过yum安装mysql-server。

准备mysql:

准备c++代码:

MyDB.h

#ifndef _MYDB_H_
#define _MYDB_H_
#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;
class MyDB{
  private:
    MYSQL *conn;
    MYSQL_RES *result;
    MYSQL_ROW row;
  public:
    MyDB();
    ~MyDB();
    bool initDb(string host,string user,string password,string db_name);
    bool execSql(string sql);
};
#endif

MyDB.cpp

#include <iostream>
#include <string>
#include "MyDB.h"
using namespace std;
MyDB::MyDB(){
   conn = mysql_init(NULL);
   if(conn==NULL){
      cout<<"error occurs "<<mysql_error(conn);
      exit(1);
   }
}


MyDB::~MyDB(){
   if(conn!=NULL){
     mysql_close(conn);
   }
}

bool MyDB::initDb(string host,string user,string password,string db_name){
   conn = mysql_real_connect(conn,host.c_str(),user.c_str(),password.c_str(),db_name.c_str(),0,NULL,0);
   if(conn==NULL){
      cout<<"error occurs "<<mysql_error(conn);
      exit(1);
   }
   return true;
}


bool MyDB::execSql(string sql){
   if(mysql_query(conn,sql.c_str())){
       cout<<"query error "<<mysql_error(conn)<<endl;
       return false;
   }else{
       result = mysql_use_result(conn);
       if(result){
           int num_fields = mysql_num_fields(result);
           int num_rows = mysql_field_count(conn);
           for(int i=0;i<num_rows;i++){
              row = mysql_fetch_row(result);
              if(row<0) break;
              for(int j=0;j<num_fields;j++){
                 cout<<row[j]<<"\t";                 
              }
              cout<<endl;
           }
       }
       mysql_free_result(result);
   }
   return true;
}

main.cpp

#include <iostream>
#include "MyDB.h"
using namespace std;
int main(){
   MyDB db;
   db.initDb("127.0.0.1","root","root","springboot");
   db.execSql("select * from xx_user");
   return 0;
}

 

编译运行:

编译命令需要考虑到libmysqlclient.so的位置,所以需要加上mysql_config --libs命令的结果。

 

利用C++代码查询数据结果,和直接在数据库中查询的结果是一样的。 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值