gpt4 book ai didi

java - 如何使用Prepared Statement进行交易?

转载 作者:行者123 更新时间:2023-11-29 04:06:12 26 4
gpt4 key购买 nike

我想借助事务在两个表中插入数据。我的查询在我的 SQL 中正常工作,但我不知道如何在 Java 代码上处理它,请帮忙。我的代码如下所示

 private Boolean executeInsertQuery(Connection conn, String schoolID, String branchID, String studentName, String parentName, String emailId, String password, String className, String section, int age, String dob, String scholarNo, String address, String contactNo, int rollType) throws SQLException {
Boolean isSuccess = false;
String statement = "START TRANSACTION;\n" +
"INSERT INTO child_details (SCHOLAR_NUMBER, SCHOOL_ID,BRANCH_ID,CHILD_NAME,ENROLLED_CLASS," +
"CHILD_SECTION,CHILD_AGE,CHILD_DOB) VALUES (?,?,?,?,?,?,?,?);\n" +
"INSERT INTO parents_details (EMAIL_ID, BRANCH_ID,SCHOOL_ID,CHILD_NAME,SCHOLAR_NUMBER,PARENT_CONTACT_NUMBER," +
"PASSWORD,ROLE_TYPE,PARENT_NAME,ADDRESS) VALUES (?,?,?,?,?,?,?,?,?,?);\n" +
"COMMIT";

PreparedStatement stmt = null;
PreparedStatement statement1 = null;
try {
stmt = conn.prepareStatement(statement);
stmt.setString(1, scholarNo);
stmt.setString(2, schoolID);
stmt.setString(3, branchID);
stmt.setString(4, studentName);
stmt.setString(5, className);
stmt.setString(6, section);
stmt.setInt(7, age);
stmt.setString(8, dob);
stmt.setString(9,emailId);
stmt.setString(10, branchID);
stmt.setString(11, schoolID);
stmt.setString(12, studentName);
stmt.setString(13, scholarNo);
stmt.setString(14, contactNo);
stmt.setString(15, password);
stmt.setInt(16, rollType);
stmt.setString(17, parentName);
stmt.setString(18, address);
int count = stmt.executeUpdate();
// int count2 = statement1.executeUpdate();

if (count > 0) {
isSuccess = true;
} else {
isSuccess = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
stmt.close();
conn.close();
}
}
return isSuccess;
}


private Connection getConnection() {

String url;
Connection conn = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://############?#######";
} else {
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/#######";
}
conn = DriverManager.getConnection(url, "root", "******");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}

这种情况下如何使用Prepared statement?

最佳答案

提交/回滚事务遵循以下模式:

conn.setAutocommit(false); // No commit per statement

try (PreparedStatement stmt1 = conn.prepareSteatement(...)) { // Automatic close.
...
try (PreparedStatement stmt2 = ... )) {
...
conn.commit();
}
} catch (SQLException ex) {
conn.rollback();
}

Try-with-resources 是一种奇怪的语法,它简化了原本需要的关闭代码。

可能需要自动生成的键 (getGeneratedKeys) 从第一个语句中获取并插入到第二个语句中 - 比如说是否有一个 AUTOINCR 字段。搜索将给出示例代码。

关于java - 如何使用Prepared Statement进行交易?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com