1. 程式人生 > >mysql c++ jdbc 示例

mysql c++ jdbc 示例

使用注意事項

 

 1 # wget https://cdn.mysql.com//Downloads/Connector-C++/mysql-connector-c++-8.0.13-linux-glibc2.12-x86-64bit.tar.gz
 2 
 3 如果出錯, 試試安裝
 4 # yum install -y boost
 5 # yum install -y boost-devel
 6 
 7 
 8 https://dev.mysql.com/downloads/connector/cpp/
 9 
10 官網提供的 Windows 版本 mysql-connector-c++-8.0.13-win 在Debug下執行Crash, 更改為Release。
11 除錯: VS工程屬性--連結器--除錯--生成除錯資訊
# g++ main.cpp JdbcHelper.cpp -I/usr/local/mysql_cpp/include/jdbc -L/usr/local/mysql_cpp/lib64 -lmysqlcppconn 

 

 

JdbcHelper.h

#pragma once
#include <iostream>
#include <string>

//#include <mysql_driver.h>
//#include <mysql_connection.h>

#include <cppconn/driver.h>
#include 
<cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> class JdbcHelper { public: /** host: tcp://192.168.6.80:23306 自動重連*/ JdbcHelper(const std::string& host, const std::string& username, const std::string
& passwd, const std::string& database); virtual ~JdbcHelper(); /** 連線 */ int jdbc_connect(bool enableSSL); /** 斷開連線 */ int jdbc_close_connect(); /** 設定是否自動提交事務 */ int jdbc_set_auto_commit(bool auto_commit); /** 提交事務 */ int jdbc_commit(); /** 建立一個儲存點 */ sql::Savepoint* jdbc_save_point(const std::string& name); /** 回滾到一個儲存點 */ int jdbc_rollback_save_point(sql::Savepoint* point); /** 釋放儲存點, 必須呼叫(記憶體洩漏) */ int jdbc_release_save_point(sql::Savepoint* point); /** stmt: setXXX(index, data), index是從1開始 返回值: 受影響的行數 affected_rows , 修改沒有發生變化, 會返回0 */ int jdbc_executeUpdate(const std::string& sql, void prepCallBack(sql::PreparedStatement* stmt), void exceptionCallBack(sql::SQLException &e)); /** stmt: setXXX(index, data), index是從1開始 返回值: 0: 成功 */ int jdbc_executeQuery(const std::string& sql, void prepCallBack(sql::PreparedStatement* stmt), void resultCallBack(sql::ResultSet* result), void exceptionCallBack(sql::SQLException &e)); protected: void printSQLException(sql::SQLException &e); private: std::string host; std::string username; std::string passwd; std::string database; sql::Driver* driver; sql::Connection* conn; };
View Code

 

JdbcHelper.cpp

#include "JdbcHelper.h"
#include <cppconn/parameter_metadata.h>


JdbcHelper::JdbcHelper(const std::string& host, const std::string& username, const std::string& passwd, const std::string& database)
{
    this->host = host;
    this->username = username;
    this->passwd = passwd;
    this->database = database;

    this->conn = NULL;

    try {
        this->driver = get_driver_instance();
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }
    
    if (driver == NULL) {
        std::cout << "driver is null" << std::endl;
    }
}


JdbcHelper::~JdbcHelper()
{
}


int JdbcHelper::jdbc_connect(bool enableSSL)
{
    if (NULL != conn) {
        return -1;
    }

    try {
        sql::ConnectOptionsMap opts;
        opts["hostName"] = this->host;
        opts["userName"] = this->username;
        opts["password"] = this->passwd;
        if (false == enableSSL) {
            // 預設使用SSL
            opts["OPT_SSL_MODE"] = sql::SSL_MODE_DISABLED;
        }
        opts["OPT_RECONNECT"] = sql::ConnectPropertyVal(true);

        this->conn = driver->connect(opts);

        if (NULL == conn) {
            printf("conn id null\n");
            return -2;
        }

        // 選擇資料庫
        sql::SQLString catalog(this->database);
        conn->setSchema(catalog);

        return 0;
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }

    return -3;
}


int JdbcHelper::jdbc_close_connect()
{
    if (conn) {
        conn->close();
        delete conn;
        conn = NULL;

        return 0;
    }

    return -1;
}

int JdbcHelper::jdbc_set_auto_commit(bool auto_commit)
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }

    try {
        conn->setAutoCommit(auto_commit);
        return 0;
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }

    return -2;
}

int JdbcHelper::jdbc_commit()
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }

    try {
        conn->commit();
        return 0;
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }

    return -2;
}

sql::Savepoint* JdbcHelper::jdbc_save_point(const std::string& name)
{
    if (NULL == conn || conn->isClosed()) {
        return NULL;
    }

    try {
        sql::SQLString savePointName(name);
        return conn->setSavepoint(savePointName);
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }

    return NULL;
}

int JdbcHelper::jdbc_rollback_save_point(sql::Savepoint* point)
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }
    if (NULL == point) {
        return -2;
    }

    try {
        conn->rollback(point);
        return 0;
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
    }

    return -3;
}

int JdbcHelper::jdbc_release_save_point(sql::Savepoint* point)
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }
    if (NULL == point) {
        return -2;
    }

    int rc = -1;
    try {
        conn->releaseSavepoint(point);
        rc = 0;
    }
    catch (sql::SQLException &e) {
        this->printSQLException(e);
        rc = -3;
    }

    delete point;

    return rc;
}

int JdbcHelper::jdbc_executeUpdate(
    const std::string& sql,
    void prepCallBack(sql::PreparedStatement* stmt),
    void exceptionCallBack(sql::SQLException &e))
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }

    int row_affected = -1;
    sql::PreparedStatement* stmt = NULL;

    try {
        do
        {
            sql::SQLString sqlString(sql);
            stmt = conn->prepareStatement(sqlString);
            if (NULL == stmt) {
                row_affected = -2;
                break;
            }

            sql::ParameterMetaData* paramMetaData = stmt->getParameterMetaData();
            if (paramMetaData) {
                if (paramMetaData->getParameterCount() > 0) {
                    if (prepCallBack) {
                        prepCallBack(stmt);
                    }
                }
            }

            row_affected = stmt->executeUpdate(); // 插入資料
        } while (false);
    }
    catch (sql::SQLException &e)
    {
        this->printSQLException(e);

        if (exceptionCallBack) {
            exceptionCallBack(e);
        }
    }

    if (stmt) {
        delete stmt;
    }

    return row_affected;
}


int JdbcHelper::jdbc_executeQuery(
    const std::string& sql,
    void prepCallBack(sql::PreparedStatement* stmt),
    void resultCallBack(sql::ResultSet* result),
    void exceptionCallBack(sql::SQLException &e))
{
    if (NULL == conn || conn->isClosed()) {
        return -1;
    }

    int rc = -1;
    sql::PreparedStatement* prep_stmt = NULL;
    sql::ResultSet* res = NULL;

    try {
        do
        {
            sql::SQLString sqlString(sql);

            sql::PreparedStatement* stmt = conn->prepareStatement(sqlString);
            if (NULL == stmt) {
                rc = -2;
                break;
            }

            if (prepCallBack) {
                sql::ParameterMetaData* paramMetaData = stmt->getParameterMetaData();
                if (paramMetaData && paramMetaData->getParameterCount() > 0) {
                    prepCallBack(stmt);
                }
            }

            res = stmt->executeQuery(); // 查詢資料
            if (NULL == res) {
                rc = -3;
                break;
            }

            if (resultCallBack) {
                resultCallBack(res);
            }

            res->close();

            rc = 0;
        } while (false);
    }
    catch (sql::SQLException &e)
    {
        // if (e.getErrorCode() == CR_SERVER_LOST) { } // in errmsg.h of mysqlclient

        if (exceptionCallBack) {
            exceptionCallBack(e);
        }
    }

    if (prep_stmt) {
        delete prep_stmt;
    }
    if (res) {
        delete res;
    }

    return rc;
}

void JdbcHelper::printSQLException(sql::SQLException &e)
{
    std::cout << "message: " << e.what() << std::endl;
    std::cout << "code: " << e.getErrorCode() << std::endl;
    std::cout << "state: " << e.getSQLState() << std::endl;
}
View Code

 

main.cpp

 

/**
  g++ main.cpp JdbcHelper.cpp -I/usr/local/mysql_cpp/include/jdbc -L/usr/local/mysql_cpp/lib64 -lmysqlcppconn 
*/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include "JdbcHelper.h"

#ifdef _MSC_VER
#pragma comment(lib, "mysqlcppconn.lib")
#endif // _MSC_VER


int main(int argc, char* argv[])
{
    JdbcHelper jdbc("tcp://192.168.6.80:23306", "root", "123456", "test");
    jdbc.jdbc_connect(true);

    std::string sql = "SELECT id, label FROM test WHERE id = ?";
    jdbc.jdbc_executeQuery(sql, [](sql::PreparedStatement* stmt) {
        stmt->setInt(1, 3);
    }, [](sql::ResultSet* result) {
        while (result->next())
        {
            int64_t id = result->getInt64(1);
            sql::SQLString label = result->getString(2);

            std::cout << "id: " << id << "  label: " << label << std::endl;
        }
    }, [](sql::SQLException &e) {
        std::cout << "message: " << e.what() << std::endl;
        std::cout << "code: " << e.getErrorCode() << std::endl;
        std::cout << "state: " << e.getSQLState() << std::endl;
    });


    sql = "INSERT INTO test(id, label) VALUES(?, ?)";
    int affected_rows = jdbc.jdbc_executeUpdate(sql, [](sql::PreparedStatement* stmt) {
        stmt->setInt64(1, 1234);
        stmt->setString(2, "label_1234");
    }, [](sql::SQLException &e) {
        std::cout << "message: " << e.what() << std::endl;
        std::cout << "code: " << e.getErrorCode() << std::endl;
        std::cout << "state: " << e.getSQLState() << std::endl;
    });

    std::cout << "  " << affected_rows << std::endl;

    jdbc.jdbc_close_connect();

    system("pause");

    return 0;
}