java-使用提交事务插入表

标签 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。 然而,当我运行该程序时,它通常会在停止之前多次打印出“添加”消息。如果我继续等待,它最终会显示:锁定时间超出,请重新启动事务

编辑:

连接方法(在不同的类中):

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!");


    }

最佳答案

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

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

作为旁注,转移到连接池并捕获异常以在发生错误时释放资源

关于java-使用提交事务插入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531135/

相关文章:

php - 如果出现连接错误,如何在表中插入一行?

python - 从 Celery 结果后端 MYSQL 查询结果

asp.net - 从一个文件导入另一个文件

Java从列中查找所有可能的组合

java - 日期格式映射到 JSON Jackson

java - 无法将 Apigee Java 对象响应转换为字符串

mysql - 将两个具有多个条件和一个最大条件的 sql 表组合在一起的最佳方法

c# - 关闭 SQLDataReader - 如何判断它们是否已关闭?

Java MYSQL错误连接关闭后不允许进行任何操作

java - 将嵌套 JSON 键转换为大写