Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

sql - One preparedstatement for multiple tables Java

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();
            }
        }

Here I am using stmt(PreparedStatement) for table PPN_WORKFLOW and CREATE_ERF?

2) the PPN_WORKFLOW table consists of more paremeters like

PPN_WORKFLOW(C1_S_Date,C2_F_Date,C2_Completed)

but I would like to update 2 and 3 parameter, So Is my code is correct.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
String insert = "INSERT INTO PPN_WORKFLOW(C2_F_Date,C2_Completed) VALUES(?,?)";
stmt = conn.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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...