Mysql Workbench is not reading records inserted through JDBC

混江龙づ霸主 提交于 2019-12-11 04:25:09

问题


Description: The autocommit value in workbench had been set to 0( zero ), then I insert a record to a table and successfully committed the transaction in Java App client through jdbc. I execute select query in the command line and the record just inserted had successfully be fetched, but execute the same query script in workbech, the record just inserted could not be fetched. only after executing the commit command in the workbench, the record can be queried.

How to repeat:

  1. set autocommit=0 in mysql workbench.
  2. insert a record to a table from java app through jdbc and commit the transaction through java.
  3. execute select query in the workbech.

Suggested fix: the workbench should read the committed records, not execute the commit command again to display already committed records through jdbc .

Below is my jdbc code for the same

    int recordInserted = 0;
    PreparedStatement prepStmt = null;
    try {

        conn = new DatabaseConnection().getSQLConnection();

        if (conn != null) {
            String sql = "INSERT INTO customerinfo (CustID, Customer_Name, Customer_License) VALUES (?, ?, ?)";

            prepStmt = conn.prepareStatement(sql);
            prepStmt.setString(1, registerRecords.getCustomerID());
            prepStmt.setString(2, registerRecords.getCustomerName());
            prepStmt.setString(3, registerRecords.getCustomerLic());

            recordInserted = prepStmt.executeUpdate();

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
             conn.close(); 
             prepStmt.close();
             conn = null;
             prepStmt=null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

回答1:


  1. set autocommit=0 in mysql workbench

This means that you will have to manually commit the transaction from Java.

  1. insert a record to a table from java app through jdbc and commit the transaction through java.

But you never actually commit from Java. You should be doing this:

conn.commit();

Full code:

if (conn != null) {
    String sql = "INSERT INTO customerinfo (CustID, Customer_Name, Customer_License) VALUES (?, ?, ?)";

    prepStmt = conn.prepareStatement(sql);
    prepStmt.setString(1, registerRecords.getCustomerID());
    prepStmt.setString(2, registerRecords.getCustomerName());
    prepStmt.setString(3, registerRecords.getCustomerLic());
    recordInserted = prepStmt.executeUpdate();

    conn.commit();
}


来源:https://stackoverflow.com/questions/40374473/mysql-workbench-is-not-reading-records-inserted-through-jdbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!