一种针对多表Java的Prepared语句 [英] One preparedstatement for multiple tables Java
问题描述
1)我可以使用一条准备好的语句将数据从Java传递到多个表吗?我正在使用JDBC驱动程序的地方.
1) Can I use one prepared statement to pass data to multiple tables from java? where I am using JDBC driver.
try
{
conn = ac.getConnection();
String insert = "INSERT INTO PPN_WORKFLOW(C2_F_Date,C2_Completed) VALUES(?,?)";
stmt = conn.prepareStatement(insert);
stmt.setDate(1, date);//question 2
stmt.setInt(2, 1);
stmt.executeUpdate();
stmt.close();
String insert2 = "INSERT INTO CREATE_ERF(Purc_Part_New_F_Date,Purc_Part_New_Completed) "
+ "VALUES(?,?)";
stmt = conn.prepareStatement(insert2);
stmt.setDate(1, date);
stmt.setInt(2,1);
stmt.executeUpdate();
}
catch(SQLException | ClassNotFoundException e) {e.printStackTrace();}
finally
{
if(stmt != null) {
stmt.close();
}
if(conn != null) {
conn.close();
}
}
我在这里为表PPN_WORKFLOW和CREATE_ERF使用stmt(PreparedStatement)吗?
Here I am using stmt(PreparedStatement) for table PPN_WORKFLOW and CREATE_ERF?
2)PPN_WORKFLOW表包含更多参数,例如
2) the PPN_WORKFLOW table consists of more paremeters like
PPN_WORKFLOW(C1_S_Date,C2_F_Date,C2_Completed)
但是我想更新2和3参数,所以我的代码正确吗?
but I would like to update 2 and 3 parameter, So Is my code is correct.
推荐答案
String insert = "INSERT INTO PPN_WORKFLOW(C2_F_Date,C2_Completed) VALUES(?,?)";
stmt = conn.prepareStatement(insert);
像工厂方法一样查看prepareStatement()
.给定输入后,它将在特定状态下返回一个对象.此时,您传递给它的输入是INSERT
语句.
Look at prepareStatement()
like a factory method. It returns an object, in a certain state, given the input. The input you pass to it, at this point, is the INSERT
statement.
尝试出于不同目的重用同一对象没有意义,因为该方法已在insert
中返回了为您提供的参数量身定制的对象.您将需要创建另一个针对该不同目的的对象.您在代码中执行的操作是什么.
Attempting to reuse the same object for a different purpose doesn't make sense, because the method has returned an object tailored for the argument you provided, in insert
. You would need to create another object, tailored to that different purpose. Which is what you do in your code.
这篇关于一种针对多表Java的Prepared语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!