2017-08-16 57 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

你摇滚的人,它工作:) –