2017-08-16 133 views
0

我想在這裏實現的是我在mysql數據庫中有一個表名total_product,我想從表中檢索SNo = 1的值並更新表中的數量。 我在GUI中使用了一個文本框,其中生成的附加產品將被寫入。 表中的輸出存儲在變量id中,並且生成的新數量存儲在變量q1中。 所以新產品的數量將是q1 = q1 + id。 我無法理解我應該在stmt.executeUpdate(sql)中使用的sql語句中放置什麼,因爲sql是一個字符串,我必須在sql字符串中將整數值傳遞給Qunty。更新表中的數據

請幫忙。

Connection conn = null ; 
    Statement stmt = null ; 

    String url = "jdbc:mysql://localhost:3306/project"; 
    String user = "root"; 
    String password = ".dpadpep"; 
    try { 

     Class.forName("com.mysql.jdbc.Driver"); 

     conn = DriverManager.getConnection(url,user,password); 

     String sql = "Select Qunty from total_product " + "where SNo = 1"; 

     stmt = conn.createStatement(); 

     ResultSet rs = stmt.executeQuery(sql); 

     int id=0; 
     int q1 = Integer.parseInt(fld1[0].getText()); 

     while(rs.next()) { 
      id = rs.getInt(1); 
      System.out.println("Quantity="+id); 
     } 

     q1 = q1+id; 

     sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1"; 
     stmt.executeUpdate(sql); 

回答

1

你並不需要顯式地檢索數據庫中的當前值,你可以簡單地直接添加額外的量:

int q1 = Integer.parseInt(fld1[0].getText()); 
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1"; 
PreparedStatement ps = conn.prepareStatement(sql); 
ps.setInt(1, q1); 
ps.executeUpdate(); 
+1

回答了這個問題,並解決什麼樣子,可能已經有人直接進入SQL注入漏洞?不錯... – user2366842

+0

你搖滾的人,它工作:) –