kowala's home

kowala's home
這裡是我的學習筆記,陸續增加中。
http://kowala21.blogspot.com

2011-06-14

實作 VC++ 連線 MySQL 資料庫


承上例

我們完成MySQL資料庫的初步建置後,接著是安裝MySQL Connector C++ 1.0.5
安裝完成後,在MySQL資料庫目錄下應該會多一個目錄
C:\Program Files\MySQL\MySQL Connector C++ 1.0.5
待會會用到,先記著。

首先,建立一個簡單的專案


選項如下


直接按完成


完成後如下圖所示


把下列程式碼複製過去,
注意:下面的#include <xxxx>符號秀出不來,我用全形符號代替
-------------------------------------------------------------------------
// dbTest.cpp : 定義主控台應用程式的進入點。
//

#include "stdafx.h"

#include <iostream>

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

using namespace std;
using namespace sql;

#define DBHOST "tcp://localhost:3306"  
#define USER "abc"  
#define PASSWORD "123"  
#define DATABASE "test"  

int _tmain(int argc, _TCHAR* argv[])
{
    const string url(DBHOST);
    const string user(USER);
    const string password(PASSWORD);
    const string database(DATABASE);

    string sql;
    Driver *driver;
    Connection *con;
    Statement *stmt;
    ResultSet *res;
    
    try{
        driver = get_driver_instance();
        con = driver -> connect(url, user, password);
        con -> setSchema(database);
        stmt = con -> createStatement();
        sql="select * from news;";
        res = stmt->executeQuery(sql);
        cout<<"列印紀錄...\n";
        while(res->next()){
            cout << res->getInt("akey") << " " << res->getString("day") << " "<< res->getString("title") << " " << res->getString("content") +"\n";
        }
    }catch(SQLException &e){
        cout<
    }

    delete res;
    delete stmt;
    delete con;
    cout<<"釋放物件 res,stmt,con\n";

    system("pause");
    return 0;
}
-------------------------------------------------------------------------

此刻編譯一定會出現一堆錯誤的,不用急,慢慢來設定環境屬性
在專案名稱按右鍵,選屬性,依下圖選取並設定。
先設定Include目錄,指向 MySQL Connector 下的 include



再來是設定 lib,指向 MySQL Connector C++ 1.0.5\lib\opt 目錄


再來是指定相依 lib,輸入 mysqlcppconn.lib


最後是copy runtime 元件到專案路徑去,此處是 dbTest\Release


這樣就可以連線 MySQL 了,迫不及待要看看執行畫面吧!


成功讀出紀錄了^^
接著測試另一種連線方式,採用 std::map 來連線
先建立專案 dbTest1,直接右鍵新增


跟剛剛一樣的步驟,輸入 dbTest1,當然,名稱是隨你高興。


然後設定為起始專案


複製下列程式碼來測試
// dbTest1.cpp : 定義主控台應用程式的進入點。
//

#include "stdafx.h"

#include <iostream>

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

using namespace std;
using namespace sql;

int _tmain(int argc, _TCHAR* argv[])
{
    std::map conProperties;
    ConnectPropertyVal val;

    val.str.val = "tcp://127.0.0.1:3306";
    conProperties[std::string("hostName")] = val;
    val.str.val = "abc";
    conProperties[std::string("userName")] = val;
    val.str.val = "123";
    conProperties[std::string("password")] = val;
    val.str.val = "test";
    conProperties[std::string("schema")] = val;

    string sql;
    Driver *driver;
    Connection *con;
    Statement *stmt;
    ResultSet *res;
    
    try{
        driver = get_driver_instance();
        con = driver -> connect(conProperties);        
        stmt = con -> createStatement();
        sql="select * from news;";
        res = stmt->executeQuery(sql);
        cout<<"使用std::map來連線,列印紀錄...\n";
        while(res->next()){
            cout << res->getInt("akey") << " " << res->getString("day") << " "<< res->getString("title") << " " << res->getString("content") +"\n";
        }
    }catch(SQLException &e){
        cout<
    }

    delete res;
    delete stmt;
    delete con;
    cout<<"釋放物件 res,stmt,con\n";

    system("pause");
    return 0;
}

這個程式碼不同於上例的地方,用紅色表示,這裡的方法是參考自JGood:
http://blog.csdn.net/JGood/archive/2010/06/10/5661339.aspx
按下執行,畫面如下。


[註] Connector C++ 1.0.5 中的變數名稱如下:
可以這樣去設定使用.
con->setClientOption("OPT_CHARSET_NAME","utf8");

hostName,userName,password,metadataUseInfoSchema,port,socket,pipe,schema,
CLIENT_COMPRESS,CLIENT_FOUND_ROWS,CLIENT_IGNORE_SIGPIPE,
CLIENT_IGNORE_SPACE,CLIENT_INTERACTIVE,CLIENT_LOCAL_FILES,
CLIENT_MULTI_RESULTS,CLIENT_MULTI_STATEMENTS,CLIENT_NO_SCHEMA,
OPT_CONNECT_TIMEOUT,OPT_READ_TIMEOUT,OPT_WRITE_TIMEOUT,
OPT_RECONNECT, OPT_SET_CHARSET_NAME,OPT_CHARSET_NAME,
REPORT_DATA_TRUNCATION,OPT_REPORT_DATA_TRUNCATION,
defaultStatementResultType,OPT_NAMED_PIPE

建立 MySQL 資料庫的基本步驟(安裝後的動作)

一開始進入MySQL,首先就是開個帳號,然後再弄個資料庫,做幾張表格,
填入一些中英文字來做查表測試,這些都完成後,就可以回到程式語言中,
撰寫程式來連線了。以下就上述步驟來個實際演練。

1.安裝完成MySQL後,就是進到資料庫中,預設的帳號是root。

C:\Users\abc>mysql -u root -p    [Enter]
Enter password: **********    [Enter]
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.49-community MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

2.先開個帳號,並設定權限,來供程式連線用,下面的設定是開放一切權限給他,
但僅能在本機執行,設定 ID/PWD = abc/123 。

mysql> grant all on *.* to abc@localhost identified by '123';

3.再來是建立資料庫了,先查看有哪些內建的資料庫。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
3 rows in set (0.01 sec)

有3個資料庫,其中有一個是 test,來看看內容。

mysql> show tables from test;
Empty set (0.02 sec)

很好,是空的資料庫,正好拿來測試用。先建個表格,再填一些資料...

mysql>  use test;
Database changed

建個表格
mysql> create table news(akey int not null primary key,day DATE,title VARCHAR(20
),content VARCHAR(50));
Query OK, 0 rows affected (0.20 sec)

查看一下剛剛建立的news表格格式

mysql> describe news;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| akey    | int(11)     | NO   | PRI | NULL    |       |
| day     | date        | YES  |     | NULL    |       |
| title   | varchar(20) | YES  |     | NULL    |       |
| content | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql> SHOW COLUMNS FROM news;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| akey    | int(11)     | NO   | PRI | NULL    |       |
| day     | date        | YES  |     | NULL    |       |
| title   | varchar(20) | YES  |     | NULL    |       |
| content | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

由上例可知,這兩個指令結果是一樣的。
describe news;
SHOW COLUMNS FROM news;

接著輸入一些紀錄,來測試查詢。

mysql> insert into news values(1,'2010-08-21','UPDATE Syntax','The UPDATE statem
ent updates columns...');
Query OK, 1 row affected (0.05 sec)

看看記錄存進去沒...
mysql> select * from news;
+------+------------+---------------+-----------------------------------------+
| akey | day        | title         | content                                 |
+------+------------+---------------+-----------------------------------------+
|    1 | 2010-08-21 | UPDATE Syntax | The UPDATE statement updates columns... |
+------+------------+---------------+-----------------------------------------+
1 row in set (0.39 sec)

很好,可以開始撰寫程式了...

MySQL 5.1参考手册