我想在我的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/