c++连接 mysql 类

cmysql.h

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <sstream>
#include <unistd.h>
#include "mysql/include/mysql.h"
using namespace std;
class Mysql{
    private:
        MYSQL *conn;
        MYSQL_RES *res;
        MYSQL_ROW row;
        
        char *server = "xxxx";
        char *user = "xxxx";
        char *password = "xxxx"; /* 此处改成你的密码 */
        char *database = "xxxx";
    public:
        void conut();
        string query(char *txt);
        void close();
};

cmysql.cpp

#include "all.h"
   void Mysql::conut(){
            conn = mysql_init(NULL);
            /* Connect to database */
            if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0)) {
            fprintf(stderr, "%s\n", mysql_error(conn));
            /* send SQL query */
            }
   }
   string Mysql::query(char *txt){
       mysql_query(conn, "SET NAMES utf8");
       mysql_query(conn, txt);
            res = mysql_use_result(conn);
            if(res<=0){
                stringstream code;
                code<<res;
                return code.str();
            }
            int k=0;
            string all;
            MYSQL_FIELD *field;
            field = mysql_fetch_fields(res);  
            all+="[";
            while ((row = mysql_fetch_row(res)) != NULL){
                if(k!=0){
                    all+=",";
                }
                all+="{";
                for(int i=0; i < res->field_count; i++){
                    stringstream ss;
                    ss<<field[i].name;
                    all+='"'+ss.str()+'"'+":"+'"';
                    if(row[i]==NULL){
                        all+="null";
                    }else{
                        all+=row[i];
                    }
                    all+='"';
                    if(i < res->field_count-1){
                        all+=',';
                    }
                }
                all+="}";
                k=2;
            }
            all+="]";
        return all;
   }
   void Mysql::close(){
       /* close connection */
            mysql_free_result(res);
            mysql_close(conn);
   }

调用

#include <cmysql.h>
main(){
Mysql my;
my.conut();
string cc=my.query("select * from user");
my.close();

}


你可能感兴趣的:(C++,mysql)