One preparedstatement for multiple tables Java

落花浮王杯 提交于 2019-12-25 18:46:34

问题


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.


回答1:


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.




回答2:


Insert values to each table at a time if the second depends on the first using try... while....

try{
        //insert to first table
        ///while true
    try{

     //insert to second table
        }finally{


        }
        }finally{
    //close resources
    }


来源:https://stackoverflow.com/questions/15276124/one-preparedstatement-for-multiple-tables-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!