直接上代码:
// MySqlTest.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
//MySQL Connector C++ 1.0.5,接口跟Oracle的OCCI长的很像(跟JDBC也像),Oracle-MySql官方网站可下载
//D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include
//D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\opt
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/exception.h>
using namespace sql;
using namespace sql::mysql;
#pragma comment(lib,"mysqlcppconn.lib")
int main(int argc, char* argv[])
{
try
{
//数据库连接
MySQL_Connection MySqlConn("localhost","root","006355");
//选择数据库(模式)
MySqlConn.setSchema("test");
Statement *pStatement = MySqlConn.createStatement();
//在Mysql数据库中,我设置的编码是GB2312,但是这里读出的仍是UTF-8编码的字符
//所以需这句来解决乱码问题
//执行无记录集返回的语句
pStatement->execute("set names gb2312");
//执行有记录集返回的语句
//注意反引号 "`",呵呵
ResultSet* pRs=pStatement->executeQuery("Select * from `Users`");
while (pRs->next())
{
cout<<pRs->getInt("id")<<endl;
string sChineseText=pRs->getString(2);
cout<<sChineseText<<":";
//输出汉字的编码
//D5 C5 C8 FD 张三 ANSI/OEM936:GBK/GB2312
//E5 BC A0 E4 B8 89 张三 UTF8
for (size_t i=0;i<sChineseText.length();i++)
{
printf("%02X ",(unsigned char)sChineseText[i]);
}
cout<<endl;
cout<<pRs->getString("password")<<endl<<endl;
}
pRs->close();
pStatement->close();
MySqlConn.close();
}
catch (SQLException& ex)
{
cout<<"Error:"<<ex.what()<<endl;
}
return 0;
}
文档参见:《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.
使用低版本MySQL服务器的话,还需MySQL C API。
--转自