gpt4 book ai didi

java - Oracle JDBC 事务管理和提交 session

转载 作者:行者123 更新时间:2023-12-01 15:54:58 25 4
gpt4 key购买 nike

假设我有以下代码

    import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestClass {

public static void main(String args[]) throws ClassNotFoundException, SQLException{

Connection database;

Class.forName("oracle.jdbc.driver.OracleDriver");
database =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:mydb", "user", "pass");

if (database.getAutoCommit())
database.setAutoCommit(false);

String insertParent = "Insert into ParentTable (parentId,name,value) values(parentSeq.nextval,?,?)";
String insertChild = "Insert into ChildTable (childId,parentId,value) values(childSeq.nextval,?,?)";


PreparedStatement addParentStmt = null;
PreparedStatement addChildStmt = null;

//Add the parent record
addParentStmt = database.prepareStatement(insertParent);

addParentStmt.setString(1,"Fruit");
addParentStmt.setString(2,"Orange");

addParentStmt.executeUpdate();

//Now retrieve the id of the parent row to insert into the child row

Statement stmt = null;
ResultSet rs = null;

stmt = database.createStatement();
rs = stmt.executeQuery("Select parentId from parentTable where value='Orange'");

//Now insert into the child table

addChildStmt = database.prepareStatement(insertChild );

if(rs.next()){
addChildStmt.setInt(1,rs.getInt("parentId"));
}

addChildStmt.setString(2,"The Orange child");

addChildStmt.executeUpdate(insertChild);

addChildStmt.close();
addParentStmt.close();

database.commit();

}

}

现在每次我运行上面的代码时都会出现以下错误。

java.sql.SQLException: ORA-01008: not all variables bound

当我调试它时,异常出现在行 addChildStmt.executeUpdate(insertChild);

我不想在插入父记录后发出提交。我的理解是,如果我在同一个 session 中,我就不必做出 promise 。上面显示的第二个插入语句是否与第一个插入语句不在同一 session 中?即使我刚刚插入了记录,为什么 rs.next() 没有返回任何值?

谢谢

编辑

要编译上述代码,oracle 中需要以下表格

create table ParentTable(parentId number, name varchar(20), value varchar(20));
create table childTable(childI number, parentid number, value varchar(20));

Oracle 中还需要两个序列parentSeq 和childSeq。

谢谢

最佳答案

由于这不是真正的代码,因此很难判断错误在哪里。但该策略本身是错误的:如果 Orange 不是唯一标识符,则它无法工作。你应该

  1. 执行 select 语句以从父序列中获取下一个值并获取父 ID
  2. 执行插入语句以插入具有此父级 ID 的父级
  3. 执行 select 语句以从子序列中获取下一个值并获取子 ID
  4. 执行插入语句以插入具有父 ID 和子 ID 的子 ID。

编辑:

现在代码没问题了,我已经找到了bug。替换

addChildStmt.executeUpdate(insertChild);

addChildStmt.executeUpdate();

(并修复 childId 列的名称)。调试器或简单的日志将显示选择查询确实返回父 ID。

关于java - Oracle JDBC 事务管理和提交 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5261034/

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