Reputation: 1
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();
Upvotes: 0
Views: 425
Reputation: 575
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
}
Upvotes: 0
Reputation: 4446
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();
}
Upvotes: 2
Reputation: 47193
What you've posted here won't work, because you're reusing the variable p
. You set up the statement for the insert, then replace it with the statement for the update, then execute that. You never execute the statement for the insert.
To fix that, either call p.executeUpdate();
before doing p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");
, or (better), use different variables for the two statements, and call executeUpdate()
on both.
Upvotes: 1
Reputation: 18704
You don't execute the first prepared statement
p.setInt(9, ar);
//MISSING: p.executeUpdate();
p=con.prepareStatement("update loan set t_os=t_os-? where accno=?");
You just overwrite it and execute the second one.
Upvotes: 2