2014-02-14 30 views
1

我有一個連接到數據庫的簡單練習。有兩種方法可以加載一批Person對象和另一個Order對象。結構上非常類似的方法,但在一個有訂單吐出:兩種類似的方法,不同的行爲setSchema在兩種情況下都不會失敗,但在第二種情況下是MySQL異常?

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的「order」前面添加模式名稱解決了這個問題。但我對此並不滿意。某處的模式名稱是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(); 

enter image description here

我希望這是真的錯字的地方,但我只是未能看到它。

+0

您是否以管理員身份進行連接?如果使用適當的連接字符串進行連接,則不需要設置模式 –

+3

'ORDER'是一個關鍵字,是'ORDER BY'的一部分,需要引用。 –

+0

讓我嘗試一下,哦上帝,我已經有了這種感覺! – Aubergine

回答

2

ORDER是關鍵字,屬於ORDER BY的一部分,需要引用;

INSERT INTO `order` (order_id,order_no,person_id) VALUES(13,2003,3) 
相關問題