mysql 连接器

来源:互联网 发布:虚拟地球仪软件 编辑:程序博客网 时间:2024/05/16 19:26

一个对mysql连接的封装,会在对象生命周期结束时自动关闭连接。

 

#ifndef __T_MYSQL_CONNECTOR_H__
#define __T_MYSQL_CONNECTOR_H__

#include <mysql.h>
#pragma comment(lib, "libmysql.lib")

class Mysql_Connector
{
private:
    MYSQL* conn_;
    bool is_valid_;

    char host_[32];
    char user_[32];
    char pwd_[32];
    char db_[32];
    int  port_;
    char charset_[32];

public:
    Mysql_Connector(const char* host, const char* user, const char* pwd,
        const char* db, int port, const char* charset="gbk", int timeout=1)
    {
        is_valid_ = false;
        conn_ = mysql_init(NULL);
        if(conn_ != NULL)
        {   
            my_bool reconnect = 1;
            if(mysql_options(conn_, MYSQL_SET_CHARSET_NAME, charset) == 0 &&
               mysql_options(conn_, MYSQL_OPT_RECONNECT, &reconnect) == 0 &&
               // mysql_options(conn_, MYSQL_OPT_WRITE_TIMEOUT, (char*)&timeout) == 0 &&
               mysql_real_connect(conn_, host, user, pwd, db, port, NULL,
                                    CLIENT_FOUND_ROWS|CLIENT_INTERACTIVE|CLIENT_TRANSACTIONS) != NULL)
                is_valid_ = true;

            strcpy(host_, host);
            strcpy(user_, user);
            strcpy(pwd_, pwd);
            strcpy(db_, db);
            port_ = port;
            strcpy(charset_, charset);

            char qstr[64];
            sprintf(qstr, "set net_write_timeout=%d", timeout);
            sprintf(qstr, "set net_read_timeout=%d", timeout*3);
            mysql_real_query(conn_, qstr, strlen(qstr));
        }
    }

    ~Mysql_Connector()
    {
        if(conn_)
            mysql_close(conn_);
    }

    bool is_valid()
    {
        return is_valid_;
    }

    bool conn_check()
    {
        if(!is_valid_)
            return false;

        if(mysql_ping(conn_) != 0)
        {
            my_bool reconnect = 1;
            mysql_close(conn_);

            if(mysql_options(conn_, MYSQL_SET_CHARSET_NAME, charset_) == 0 &&
                mysql_real_connect(conn_, host_, user_, pwd_, db_, port_, NULL,
                                    CLIENT_FOUND_ROWS|CLIENT_INTERACTIVE|CLIENT_TRANSACTIONS) != NULL &&
                mysql_options(conn_, MYSQL_OPT_RECONNECT, &reconnect) == 0)
                is_valid_ = true;
        }   

        return is_valid_;
    }

    MYSQL* conn()
    {
    //    conn_check(); // reconnect if needed
        return conn_;
    }

    int query(const char* qstr)
    {
        if(conn_)
            return mysql_real_query(conn_, qstr, strlen(qstr));
        else
            return -1;
    }

    int insert_id()
    {
        return mysql_insert_id(conn_);
    }

    std::string error()
    {
        if(conn_)
            return std::string(mysql_error(conn_));
        else
            return std::string("unlinked");
    }
};

#endif // __T_MYSQL_CONNECTOR_H__