2015年7月19日 星期日

c++ 存取 mysql 資料庫

Beginning Linux Programming》上頭寫的是C,比較不那麼好記憶,於是我上網搜尋了c++的相關用法。很幸運的,MySQL官方就有提供API可以給C++使用,它感覺使用了物件導向的概念,記憶上比較輕鬆,這篇筆記也是在參考它以後所寫的。(官方的文件也寫得很簡明易懂,建議可以看一下)

假設我想存取的資料庫在本機,有資料表children如下:












則我可以使用以下程式來讀寫

#include<iostream>
#include <stdlib.h>
#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()
{
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;

        driver = get_driver_instance();
        con = driver->connect("localhost", "username", "password");
        con->setSchema("database");

        stmt = con->createStatement();
        stmt->execute("INSERT INTO children(no,fname,age) VALUE(8,'Amy',5)");
//      execute 是用於無回傳值的情況,executeQuery則是有回傳值的情況使用
res = stmt->executeQuery("SELECT * from children");

        while(res->next())
        {
                cout << "id = "<<res->getInt("no")<<"\t";
                cout << "fname = "<<res->getString("fname")<<"\t";
                cout << "age = " <<res->getString(3)<<"\t";
                cout <<endl;
        }
//      res.getInt和res.getString的參數也可以接收正整數,代表第幾個column
return 0; }

這小程式會新增一組資料,並回傳、顯示整個資料表

實際使用時記得得加上try,以投擲與接收錯誤資訊。

編譯時必須加上 -lmysqlcppconn

安裝時我是直接 sudo apt-get install libmysql*

沒有留言:

張貼留言