1 // MySqlTest.cpp : 定义控制台应用程序的入口点。
2 //
3
4 #include <iostream>
5 using namespace std;
6
7 //MySQL Connector C++ 1.0.5,接口跟Oracle的OCCI长的很像(跟JDBC也像),Oracle-MySql官方网站可下载
8 //D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include
9 //D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\opt
10
11 #include <mysql_connection.h>
12 #include <cppconn/statement.h>
13 #include <cppconn/exception.h>
14 using namespace sql;
15 using namespace sql::mysql;
16
17 #pragma comment(lib,"mysqlcppconn.lib")
18
19 int main(int argc, char* argv[])
20 {
21 try
22 {
23 //数据库连接
24 MySQL_Connection MySqlConn("localhost","root","006355");
25
26 //选择数据库(模式)
27 MySqlConn.setSchema("test");
28
29 Statement *pStatement = MySqlConn.createStatement();
30
31 //在Mysql数据库中,我设置的编码是GB2312,但是这里读出的仍是UTF-8编码的字符
32 //所以需这句来解决乱码问题
33
34 //执行无记录集返回的语句
35 pStatement->execute("set names gb2312");
36
37 //执行有记录集返回的语句
38 //注意反引号 "`",呵呵
39 ResultSet* pRs=pStatement->executeQuery("Select * from `Users`");
40
41 while (pRs->next())
42 {
43 cout<<pRs->getInt("id")<<endl;
44
45
46 string sChineseText=pRs->getString(2);
47 cout<<sChineseText<<":";
48
49 //输出汉字的编码
50 //D5 C5 C8 FD 张三 ANSI/OEM936:GBK/GB2312
51 //E5 BC A0 E4 B8 89 张三 UTF8
52 for (size_t i=0;i<sChineseText.length();i++)
53 {
54 printf("%02X ",(unsigned char)sChineseText[i]);
55 }
56 cout<<endl;
57
58 cout<<pRs->getString("password")<<endl<<endl;
59 }
60
61 pRs->close();
62 pStatement->close();
63 MySqlConn.close();
64 }
65 catch (SQLException& ex)
66 {
67 cout<<"Error:"<<ex.what()<<endl;
68 }
69
70 return 0;
71 }
文档参见:《MySQL 5.5 Reference Manual》
21.5. MySQL Connector/C++
可惜的是:
22.5.12.2: Which MySQL Server version(s) is MySQL Connector/C++ compatible with?
MySQL Connector/C++ fully supports MySQL Server version 5.1 and later.
可惜的是:
22.5.12.2: Which MySQL Server version(s) is MySQL Connector/C++ compatible with?
MySQL Connector/C++ fully supports MySQL Server version 5.1 and later.
使用低版本MySQL服务器的话,还需MySQL C API。