gpt4 book ai didi

java - 两种相似的方法,不同的行为 setSchema 都没有失败,但第二种情况下是 MySQL 异常?

转载 作者:行者123 更新时间:2023-11-29 06:40:35 28 4
gpt4 key购买 nike

我有一个连接数据库的简单练习。有两种方法,一种加载一批 Person 对象,另一种加载 Order 对象。结构上非常相似的方法,但带有命令的方法吐出:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (order_id,order_no,person_id) VALUES(13,2003,3)' at line 1 

方法 2 本身的准备语句非常简化 - 因为我试图找出问题所在。事实证明,在 PreparedStatement 中的“顺序”前面添加模式名称可以解决问题。但我对此并不满意。某处模式名称是 ps 而某处 setSchema 显然是错误的。

问题是为什么 setSchema 在第一个方法没有这样的异常并按预期执行时在第二个方法中不起作用?我进行了调试,连接实例的数据库字段显示显示“ordermanagement”,这是我的模式的正确名称。

最后我单独运行了测试,所以连接没有被重用。

方法一(可行,没问题)

public int[] personBatchInsert(List<Person> personList) throws SQLException {
int[] insertStatuses = null;

try {
obtainedConnection.setSchema("ordermanagement");
ps = obtainedConnection
.prepareStatement("INSERT INTO person (person_id,last_name,first_name, street,city) VALUES(?,?,?,?,?)");
obtainedConnection.setAutoCommit(false);
for (Person person : personList) {

ps.setLong(1, person.getPersonId());
ps.setString(2, person.getLastName());
ps.setString(3, person.getName());
ps.setString(4, person.getStreet());
ps.setString(5, person.getCity());
ps.addBatch();

}

insertStatuses = ps.executeBatch();
obtainedConnection.commit();

方法二(抛出异常)

public int[] orderBatchInsert(List<Order> orderList) throws SQLException {
int[] insertStatuses = null;

try {
obtainedConnection.setSchema("ordermanagement");
ps = obtainedConnection
.prepareStatement("INSERT INTO order (order_id,order_no,person_id) VALUES(13,2003,3)");
obtainedConnection.setAutoCommit(false);

ps.execute(); // here exception is triggered
obtainedConnection.commit();

enter image description here

我希望这真的是某个地方的错字,但我就是没看到。

最佳答案

ORDER是关键字,是ORDER BY的一部分,需要加引号;

INSERT INTO `order` (order_id,order_no,person_id) VALUES(13,2003,3)

关于java - 两种相似的方法,不同的行为 setSchema 都没有失败,但第二种情况下是 MySQL 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788443/

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