//
S:~在官方给的例子基础上进行修改后的例子
#include
#include
#include
#include
#include
"mysql_connection.h"
#include
#include
#include
#include
#include
using
namespace
std;
int
main(void)
try
{
sql::Driver
*driver;
sql::Connection
*con;
sql::Statement
*stmt;
sql::ResultSet
*res;
driver
=
0;
/*
Create
a
connection
*/
driver
=
get_driver_instance();
//
获取连接驱动
con
=
driver->connect("tcp://localhost:3306",
"root",
"********");
//
ip,用户,密码
/*
Connect
to
the
MySQL
test
database
*/
con->setSchema("test");
//
选择数据库
stmt
=
con->createStatement();
//
创建查询语句
res
=
stmt->executeQuery("select
*
from
a");
//
执行查询
while
(res->next())
{
cout
<<
"\t...
MySQL
replies:
";
/*
Access
column
data
by
alias
or
column
name
*/
cout
<<
res->getString(1)
<<
'\t'
<<
res->getString(2)
<<
endl;
//
输出1,2列
}
delete
res;
delete
stmt;
delete
con;
return
EXIT_SUCCESS;
}
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;
}
运行截图:
mysql
connector/c++
文档(包括例子):
http://dev.mysql.com/doc/refman/5.1/en/connector-cpp.html
mysql
connector/c++
api下载:
http://dev.mysql.com/downloads/connector/cpp/
下载以后lib和include文件夹直接copy到你vc的lib和include里
然后工程库引用里添加对mysqlcppconn.lib的引用
可能要将mysqlcppconn.dll放到c:\windows文件夹下
具体可以参考这里:
http://hi.baidu.com/buptyoyo/blog/item/11ddf212cdaef40b213f2e3d.html
另外注意目前有个已知的因debug和release模式下string长度不同而引起的bug:
http://bugs.mysql.com/bug.php?id=44272
所以代码要在release下编译运行,driver->connect才能连接成功