使用BEGIN和COMMIT java在多个表上插入MySql

时间:2015-04-03 12:13:44

标签: java 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 );

你们能帮我弄清楚错误吗?

1 个答案:

答案 0 :(得分: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
}