0

i need to update a table automatically after the insert of another table is successful. i am using prepared statement to do this, and tried couple of ways to do but dint work out. can some one please help me out on this. the code is given following

            try
                {   
                    p=con.prepareStatement("insert into receipt values(?,?,?,?,?,?,?,?,?)");
                    p.setInt(1, rn);
                    p.setDate(2, new java.sql.Date(rd.getTime()));
                    p.setInt(3, ag);
                    p.setInt(4, an);
                    p.setString(5, name);
                    p.setString(6, street);
                    p.setString(7, city);
                    p.setInt(8, pinno);
                    p.setInt(9, ar);
                    p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");
                    p.setInt(1, ar);
                    p.setInt(2, an);
                    p.executeUpdate();

                    /*try
                    {
                        p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");
                        p.setInt(1, Integer.parseInt(art.getText()));
                        p.setInt(2, Integer.parseInt(ant.getText()));
                        p.executeUpdate();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }*/

                    status.setForeground(Color.BLUE);
                    status.setText("Successfully Added");
                }
                catch (Exception e) 
                {
                    e.printStackTrace();
                    status.setForeground(Color.RED);
                    status.setText("Enter proper values");
                }

for me it execution get stucks after p.executeUpdate();

4

4 回答 4

2

您不执行第一个准备好的语句

  p.setInt(9, ar);
  //MISSING: p.executeUpdate();
  p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");

您只需覆盖它并执行第二个。

于 2012-03-19T13:21:39.383 回答
2

You should be using transactions for this: http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

try {
 con.setAutoCommit(false);

 p=con.prepareStatement(....)
 ....
 p.executeUpdate();

 //Second statement
 p=con.prepareStatement(....)
 ....
 p.executeUpdate();

 con.commit();

 catch(..) {
  con.rollback();
 }
于 2012-03-19T13:26:57.007 回答
1

您在此处发布的内容将不起作用,因为您正在重用变量p. 您设置了插入语句,然后将其替换为更新语句,然后执行该语句。您永远不会执行插入语句。

为了解决这个问题,要么p.executeUpdate();在做之前调用p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");,要么(更好),为这两个语句使用不同的变量,并同时调用executeUpdate()两者。

于 2012-03-19T13:22:13.787 回答
0
you can first successfully execute the first query then you continue to the update...
you can use


    try{
    //work first execution
    ///while true
    try{

 //update code
    }finally{


    }
    }finally{
//close resources
    }
于 2012-03-19T16:07:51.747 回答