c++ - 从 C++ 连接到 MySQL,getString() 无法正常工作
问题描述
#include <stdlib.h>
#include <iostream>
#include<mysql/jdbc.h>
#include<string>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
//#pragma comment(lib,"mysqlcppconn8.lib")
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' >> AS _message'..." << endl;
try {
sql::Connection* con;
sql::Statement* stmt;
sql::ResultSet* res;
/* Create a connection */
sql::Driver* driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "v3952003");
/* Connect to the MySQL test database */
con->setSchema("bank_db");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT * from account");
string bankCode="";
while (res->next()) {
cout << "\t... MySQL replies: " << endl;
/* Access column data by alias or column name */
cout << "No : "<<res->getInt(1) << endl;
cout << "BankCode : " << res->getString(2) << endl;
cout << "AccountNo : " << res->getString(3) << endl;
cout << "CardNo : " << res->getString(4) << endl;
cout << "Pwd : " << res->getString(5) << endl;
cout << "Name : " << res->getString(6) << endl;
cout << "Deposit : " << res->getInt(7) << endl;
cout << "\t... MySQL says it again: ";
/* Access column data by numeric offset, 1 is the first column */
}
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;
}
cout << endl;
return EXIT_SUCCESS;
}
在此代码中,getInt() 返回正确的值,但 getString() 无法正常工作。
getString() 返回奇怪的值。我不知道有什么问题。
我尝试通过在 while() 中设置断点进行调试。
cout << "BankCode : " << res->getString(2) << endl;
而不是这条线,
String bankCode="";
在 while() 之前写过这个,
bankCode.append(res->getString(2));
cout<<bankCode<<endl;
并将这些写在 while() 中,
但它也不起作用。
因为 getString() 可能无法正常工作,所以溢出代码是没有用的。
解决方案
推荐阅读
- sql - 尝试通过传递数据库名称和模式以及表名来获取列
- c++ - 调用“enqueue_work”时出现问题 - vorbrodt thread_pool
- html - 为什么 z 轴在 transform-origin 属性中不起作用?
- jenkins - Jenkinsfile 不考虑分支条件
- java - 如何正确限制 JVM 的内存使用量?
- ios - 从github下载为zip文件后如何将应用程序源代码添加到xcode
- flutter - 如何使用 StreamBuilder 在 pdf 中打印来自 Firebase Storage 的图像
- node.js - nodejs twitter如何结束流并开始一个新的
- python - 从输出中获取空白字符串
- java - 如何在 Heroku 中将 JDK 1.8 更改为 JDK 11?