簡體   English   中英

在Java中插入成功后自動更新

[英]update automatically after insert is successful in java

插入另一個表成功后,我需要自動更新一個表。 我正在使用准備好的語句來執行此操作,並嘗試了幾種方法來完成工作,但努力工作。 有人可以幫我這個忙嗎? 代碼如下

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

對我來說,它在p.executeUpdate()之后執行陷入困境。

您不執行第一個准備好的語句

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

您只需覆蓋它並執行第二個。

您應該為此使用事務: 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();
 }

您在此處發布的內容無效,因為您正在重用變量p 設置插入語句,然后將其替換為更新語句,然后執行該語句。 您永遠不會執行插入語句。

要解決此問題,請調用p.executeUpdate(); 在執行p=con.prepareStatement("update loan set t_os=t_os-? where accno=?"); ,或(更好),對這兩個語句使用不同的變量,然后對兩個語句都調用executeUpdate()

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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM