c mysql query 错误,C ++ executeQuery()错误显示表中的MySQL数据

I need some help. I had this code (below), to add data to a MySQL table and then return that same table. The code is doing fine, when I run it it adds the column to the MySQL table BUT it stops, with the error:

SQL error. Error message:

Literally blank. If I use a SELECT statement rather than an INCLUDE one in executeQuery(), it runs with no problem and no error message, just displays my table (or parts of it). What am I missing?

I am using Visual Studios 2015, and MySQL Server.

The end-goal is to connect an API with an SQL table using C++, to record data according to a specific timespan. This is one of the first steps, just to make sure that I can link MySQL with C++ properly.

Sorry if this post is poorly written, first time here and definitely not an experienced programmer... Also, I looked into other threads, but as this is so specific I could not find them helpful.

// Standard C++ includes

#include

#include

#include

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;

}

Thanks in advance

解决方案

An INSERT is not a query. Try using executeUpdate() instead of executeQuery().

Replace this line

res = stmt->executeQuery("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");

with the following lines (you may need an additional .h file):

sql::PreparedStatement *pstmt;

pstmt = con->prepareStatement("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");

res = pstmt->executeUpdate();

delete pstmt;

Look at the official MySQL example here for an example of the concept.

You may also try using execute(), as shown in this Stackoverflow question. The function execute() is used for generic SQL commands, but may not be as verbose in its return value as more specified functions (it returns a boolean).

你可以使用Java JDBC API来连接MySQL数据库,然后使用SELECT语句从表中检索数据。以下是一个简单的示例代码,可以在Java Swing应用程序中使用按键来搜索MySQL数据: ```java import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; public class SearchData extends JFrame implements ActionListener { private JTextField searchField; private JTextArea resultArea; private JButton searchButton; public SearchData() { super("Search MySQL Data"); setLayout(new BorderLayout()); searchField = new JTextField(); add(searchField, BorderLayout.NORTH); resultArea = new JTextArea(); add(new JScrollPane(resultArea), BorderLayout.CENTER); searchButton = new JButton("Search"); searchButton.addActionListener(this); add(searchButton, BorderLayout.SOUTH); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { try { // Connect to MySQL database Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); // Create a statement object Statement stmt = con.createStatement(); // Execute the SELECT query String query = "SELECT * FROM mytable WHERE field LIKE '%" + searchField.getText() + "%'"; ResultSet rs = stmt.executeQuery(query); // Display the result in the text area resultArea.setText(""); while (rs.next()) { resultArea.append(rs.getString("field1") + "\t" + rs.getString("field2") + "\n"); } // Close the result set, statement, and connection rs.close(); stmt.close(); con.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { new SearchData(); } } ``` 在上面的代码中,当用户单击“Search”按钮时,将调用actionPerformed方法。该方法将从文本框中获取搜索字符串,然后使用LIKE运算符在MySQL表中搜索匹配的行。查询的结果将在文本区域中显示。注意,这只是一个简单的示例,你需要根据自己的需求进行修改和改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值