c ++连接到在线数据库

时间:2016-06-07 09:34:27

标签: c++ mysql database

我正在试图弄清楚如何使用c ++连接到在线数据库。我试过谷歌,但我只能找到连接到本地主机的方法。

我的代码如下:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
    cout << endl;
    cout << "Running 'SELECT 'Hello World!' 'AS _message'..." << endl;

    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;

        // Create a connection
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
        // Connect to the MySQL test database
        con->setSchema("test");

        stmt = con->createStatement();
        res = stmt->executeQuery("SELECT 'Hello World!'"); // replace with     your statement
        while (res->next()) {
            cout << "\t... MySQL replies: ";
            // Access column data by alias or column name 
            cout << res->getString("_message") << endl;
            cout << "\t... MySQL says it again: ";
            // Access column fata by numeric offset, 1 is the first column 
            cout << res->getString(1) << endl;
        }
        delete res;
        delete stmt;
        delete con;

    }
    catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    cout << endl;

    return EXIT_SUCCESS;
}

con = driver->connect("tcp://127.0.0.1:3306", "root", "root");连接到我的电脑上的mysql数据库(我想??)。如何连接到在线mysql数据库呢?我有一个免费的webhost站点,数据库所在的站点,我想向它发出查询。我需要一个完全不同的库吗?

0 个答案:

没有答案