2010年4月9日星期五

使用mysql connector/C++查询mysql数据库

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

using namespace std;

void RunConnectMySQL()  

    try{
        //sql::Driver *driver;
        sql::mysql::MySQL_Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt; 
        sql::ResultSet *result; 

        //driver = get_driver_instance();
        driver=sql::mysql::get_mysql_driver_instance();

        con = driver->connect("tcp://127.0.0.1:3306", "user", "password"); 

        stmt = con->createStatement(); 
        stmt->execute("use doclibexp"); 

        result = stmt->executeQuery("select * from nations"); 

        while(result->next()) 
        { 
            string nation = result->getString("Nation"); 
            string notation = result->getString("Notation"); 
            cout << nation << " : " << notation << endl;
        } 
        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;
    }

int main(int argc, char **argv) 

    RunConnectMySQL(); 
    getchar(); 
    return 0; 

没有评论:

发表评论