java-使用Commit Transaction插入表

时间:2018-11-29 02:50:21

标签: java mysql database-connection

我想在我的Java程序中启动事务以插入到MYSQL的表中。

我的代码:

 public void index(String path) throws Exception {   

        PDDocument document = PDDocument.load(new File(path));

            if (!document.isEncrypted()) {

                PDFTextStripper tStripper = new PDFTextStripper();
                String pdfFileInText = tStripper.getText(document);
                String lines[] = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    String[] words = line.split(" ");


                    String sql="insert IGNORE into  test.indextable values (?,?);";

                       preparedStatement = con.connect().prepareStatement(sql);
                     int i=0;
                    for (String word : words) {

                        // check if one or more special characters at end of string then remove OR
                        // check special characters in beginning of the string then remove
                    // insert every word directly to table db
                      word=word.replaceAll("([\\W]+$)|(^[\\W]+)", "");
                        preparedStatement.setString(1, path);
                        preparedStatement.setString(2, word);

                        preparedStatement.executeUpdate();
        System.out.print("Add ");



                }


            }

        con.connect().commit();
        preparedStatement.close();
     con.connect().close();

        System.out.println("Successfully commited changes to the database!");

我在连接类中将AutoCommit设置为false。 但是,当我运行该程序时,通常会在停止该消息之前多次打印出“添加”消息。如果我一直等待,它最终会说:Lock Time Exceeding,please restart transaction

编辑:

连接方法(在另一个类中):

public Connection connect() throws Exception {
    Properties props=new Properties();


    InputStream in = getClass().getResourceAsStream("/db.properties");

    props.load(in);
    in.close();



    String driver = props.getProperty("jdbc.driver");
    if(driver!=null){
        Class.forName(driver);

    }

    String url=props.getProperty("jdbc.url");
    String username=props.getProperty("jdbc.username");
    String password=props.getProperty("jdbc.password");

    Connection con = DriverManager.getConnection(url,username,password);
    //con.setAutoCommit(false);

    return con;

}

回滚功能:

 public void rollbackEntries() throws Exception {

       con.connect().rollback();
       System.out.println("Successfully rolled back changes from the database!");


    }

1 个答案:

答案 0 :(得分:1)

您应使用相同的连接进行提交

 Connection con =con.connect();
 ....
 con.commit();
 con.close();

此外,请移至连接池并捕获异常以在发生错误时释放资源