2015-04-03 30 views
0

此查詢是否可用於java?使用BEGIN和COMMIT在多個表上插入MySql java

"BEGIN;" 
+ "INSERT INTO product(code, name, description, category_id) " 
+ "VALUES(?,?,?,?);" 
+ "INSERT INTO inventory_item(quantity, price, product_id) " 
+ "VALUES(?,?,LAST_INSERT_ID());" 
+ "COMMIT;"; 

我用它上一個PreparedStatement,它真的吃了我的時間只是爲了找出錯誤我dbUnit表示,目前在語句中的錯誤

com.example.dao.exception.DataAccessException: 
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 'INSERT INTO product(code, name, description, 
category_id) VALUES('00003','lemon ' at line 1 
    at 
com.example.dao.InventoryDaoImpl.addInventoryItem(InventoryDaoImpl.java:126) 

我無法打印的PreparedStatement上我試過的控制檯

PreparedStatement statement = 
     connection.prepareStatement(FIND_INVENTORY_ITEM_BY_PRODUCT_CODE_QUERY); 
System.out.print(statement); 

你們可以幫我找出錯誤嗎?

+0

我想,你有'END'在你開始-end塊的結束? ;) – rzysia 2015-04-03 12:41:11

+0

我已經有'COMMIT' – user2785929 2015-04-03 12:56:58

+0

當你在mysql服務器上手動嘗試時,相同的查詢是否工作? – frost287 2015-04-03 13:38:33

回答

0

可能不是方式,但是這一直爲我工作:

List<String> sqlStatements = new ArrayList<String>(); 
// stuff your statements into this list 
// (I'm often reading them from some file. The file often 
// contains blank lines, comments and semicolons, which I 
// strip out.) 
Statement stmt = null; 
try { 
    dbConn.setAutoCommit(false); 
    stmt = dbConn.prepareStatement(); 
    for (String sql : sqlStatements) { 
     logger.debug("\t"+sql); 
     stmt.addBatch(sql); 
    } 
    stmt.executeBatch(); 
    dbConn.commit(); 
} catch (Exception e) { 
    // handle exceptions 
} finally { 
    // close statement 
}