我需要在两个不同的表中插入数据,所以我不理解两个对象如何交互以插入数据。我有两个类class a和class b都有两个方法addA和addb类a由classB对象组成所以在我的方法addA我创建一个新的classB对象并调用addB方法,在这两个方法中我使用连接还有一个带有提交的preparedStatement,但如果方法addB doesen工作,我需要做回滚,有人可以给我一个这样的例子吗?谢谢!
EXAMPLE OF CLASS A
class a{
int id;
String name;
int age;
a(String name, int age){
this.name= name;
this.age=age;
}
public boolean addA( ) throws Exception {
conecctions.Conn.getConnection();
Statement stmt = null;
Connection conection = conecctions.Conn.connection;
Boolean result = false;
try {
conection.setAutoCommit(false);
stmt = conection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String addnew= "insert into table_a values (?,?)"
PreparedStatement prepared1= conection.prepareStatement(addnew);
prepared1.setString(1, "name");
prepared2.setInt(2, 25);
prepared1.executeUpdate();
ResultSet keys = prepared1.getGeneratedKeys();
int lastKey = 1;
while (keys.next()) {
lastKey = keys.getInt(1);
}
this.id=lastKey;
result = true;
conection.commit();
b newB= new b(this.id, this.age);
newb.addB();
catch (Exception e2) {
if (conection != null) {
try {
System.out.println("rollback");
} catch (Exception e1) {
e1.printStackTrace();
}
}
e2.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conection != null)
conection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return result;
}
B类的例子
class b{
int id;
int idA;
int ageA;
b(String idA, int ageA){
this.idA= idA;
this.ageA=ageA;
}
public boolean addB( ) throws Exception {
conecctions.Conn.getConnection();
Statement stmt = null;
Connection conection = conecctions.Conn.connection;
Boolean result = false;
try {
conection.setAutoCommit(false);
stmt = conection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String addnew= "insert into table_b values (?,?)"
PreparedStatement prepared2= conection.prepareStatement(addnew);
prepared2.setInt(1, a_id);
prepared2.setInt(2, a_age);
prepared2.executeUpdate();
result = true;
conection.commit();
catch (Exception e2) {
if (conection != null) {
try {
System.out.println("rollback");
} catch (Exception e1) {
e1.printStackTrace();
}
}
e2.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conection != null)
conection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return result;
}
只是一个例子
答案 0 :(得分:0)
最简单的方法是制作2个DAO类:1个将数据插入第一个表,第2个DAO是将数据插入另一个表。您的DAO类应扩展DAO抽象类,您可以在其中启动连接,并使用disconnect()方法断开连接,结果集,预表示。
您要插入的数据,来自何处?
答案 1 :(得分:0)