2014-06-19 23:01:52|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, MySQL, 数据库|来源:唯设编程网
// TestMysql.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "iostream" #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { try { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; driver = get_driver_instance(); //连接数据库 con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); //选择要连接的数据库 con->setSchema("sj"); //新建一个执行语句 stmt = con->createStatement(); //执行语句并返回结果集 res = stmt->executeQuery("SELECT * from user"); //遍历结果集 while (res->next()) { //这里的ID是user表中的字段名 cout << res->getString("id") << endl; } //读取一个字符,目的是让CMD窗口停留,查看输出信息。 getchar(); delete res; delete stmt; delete con; } 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; } return EXIT_SUCCESS; }