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

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

你们能帮我找出错误吗?

最佳答案

可能不是这样,但这对我来说一直有效:

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
}

关于java - MySql使用BEGIN和COMMIT java在多个表上插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432007/

相关文章:

java - 为什么 SimpleDateFormat 将 unix 日期显示为 1969 年 12 月 31 日?

java - 如何从 tflite 模型输出形状 [1, 28, 28,1] 的数组作为 android 中的图像

java - Play Framework 和 jdbc 阻塞 io 调用是否有主要的扩展限制

mysql - 无法连接到通过 docker-compose 创建的 MySQL docker 容器

mysql - 没有 www 的服务器返回 404

php - 将行与 mysql 中的最新日期连接起来

sql - 优化 SQL 距离查询

Mysql:1 个表定期崩溃

java - 如何在 JDialog 上设置 MaximumSize?

java - JiBX 框架 jar 不在类路径中