【发布时间】:2016-03-23 18:33:49
【问题描述】:
我需要一些帮助。我有这段代码(如下),将数据添加到 MySQL 表中,然后返回同一个表。代码运行良好,当我运行它时,它将列添加到 MySQL 表中但它停止了,并出现错误:
SQL error. Error message:
字面意思是空白。如果我在executeQuery() 中使用SELECT 语句而不是INCLUDE 语句,它运行没有问题,也没有错误消息,只显示我的表(或部分表)。我错过了什么?
我正在使用 Visual Studios 2015 和 MySQL Server。
最终目标是使用 C++ 将 API 与 SQL 表连接起来,以根据特定时间跨度记录数据。这是第一步,只是为了确保我可以正确链接 MySQL 和 C++。
对不起,如果这篇文章写得不好,第一次来这里,绝对不是一个有经验的程序员......另外,我查看了其他线程,但由于这太具体了,我找不到它们有帮助。
// Standard C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")
// Specify our connection target and credentials
const string server = "127.0.0.1:3306";
const string username = "root";
const string password = "root";
const string database = "dbex";
const string table = "tbex";
int main()
{
sql::Driver *driver; // Create a pointer to a MySQL driver object
sql::Connection *dbConn; // Create a pointer to a database connection object
sql::Statement *stmt; // Create a pointer to a Statement object to hold our SQL commands
sql::ResultSet *res; // Create a pointer to a ResultSet object to hold the results of any queries we run
// Try to get a driver to use to connect to our DBMS
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
// Try to connect to the DBMS server
try
{
dbConn = driver->connect(server, username, password);
dbConn->setSchema(database);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement();
// Try to query the database
try
{
//stmt->execute("USE " + database); // Select which database to use. Notice that we use "execute" to perform a command.
res = stmt->executeQuery("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");
res = stmt->executeQuery("SELECT * FROM cars"); // Perform a query and get the results. Notice that we use "executeQuery" to get results back
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
// While there are still results (i.e. rows/records) in our result set...
while (res->next())
{
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete dbConn;
system("pause");
return 0;
}
提前致谢
【问题讨论】:
标签: c++ mysql sql visual-studio visual-studio-2015