gpt4 book ai didi

C++向MySQL插入数据返回错误

转载 作者:行者123 更新时间:2023-11-29 00:03:03 25 4
gpt4 key购买 nike

我从 MySQL 页面修改了一组代码来测试输入数据到 MySQL 表“列表”中。程序退出并出现以下错误

terminate called after throwing an instance of 'sql::SQLException'
what():
Aborted

我查了一下表,不知怎么的,数据插入成功了。我修改了这个程序以使用 for 循环重复插入数据,但最终循环在第一次迭代后退出(程序在第一次插入期间被迫退出)。

我也尝试过硬编码查询,它在 MySQL 中手动输入,但仍然有同样的问题。

#include <stdlib.h>
#include <iostream>
#include <string>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <mysql_driver.h>

using namespace std;

int main(void){
cout << endl;
cout << "Running test insert" << endl;

sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;

/* Create a connection */
driver = get_driver_instance();
con = driver->connect("localhost", "dev", "1234");

/* Connect to the MySQL test database */
con->setSchema("million");

string data("abc1234567890");

stmt = con->createStatement();
res = stmt->executeQuery("INSERT INTO list VALUES('0','" +
data + "','" + data +"','" + data + "','" + data + "','" + data + "');");
}
// replace with your statement
delete res;
delete stmt;
delete con;

cout << endl;

return EXIT_SUCCESS;

}

用这个 try{} catch

try{....}
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;}

输出这个错误信息

# ERR: SQLException in test.cpp(main) on line 54
# ERR: (MySQL error code: 0, SQLState: 00000 )

最佳答案

sql::SQLException 被抛出是因为 executeQuery() 函数应该在 SQL 查询之后返回一个 sql::ResultSet执行(例如 SELECT 语句)。对于不返回任何数据库选择(例如 CREATE、UPDATE)的 SQL 查询,还有另一个函数 execute()

原始答案可以在这里找到:MySQL Query executes but throws exception

关于C++向MySQL插入数据返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28834038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com