繁体   English   中英

两种相似的方法,不同的行为setSchema不会同时失败,但是第二种情况是MySQL异常吗?

[英]Two similar methods, different behaviors setSchema does not fail in both, but MySQL exception in second case?

我有一个连接数据库的简单练习。 有两种方法,其中一种加载一批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”,这是我的架构的正确名称。

最终,我单独运行了测试,因此连接不会被重用。

方法1(有效,没问题)

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();

方法2(引发异常)

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();

在此处输入图片说明

我希望这确实是一个错字,但我只是看不到它。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM