如何使用变量更新列?

时间:2013-05-19 16:13:05

标签: java mysql sql-update

我有两个问题:

1)如何在UPDATE Query中调用变量,因为我想使用同一行来更新大量列。 我在INSERT和SELECT中完成了它,但它在UPDATE中导致错误 我在哪里使用:

string x="term";
 try{

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/ourproject?useUnicode=true&characterEncoding=utf8&user=luffy&password=111111");
    Statement stmt=(Statement) con.createStatement();
    String select = "SELECT ('" + x  + "') FROM test WHERE doc=0"; 
    stmt.executeUpdate(select);
   }
   catch(Exception e)
   {
    e.printStackTrace();   
   }

2)如果我可以调用变量,如何通过添加1来更新其值? 我试过这个并且有效:

try{

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/ourproject?useUnicode=true&characterEncoding=utf8&user=luffy&password=111111");
    Statement stmt=(Statement) con.createStatement();
    String update = "UPDATE test SET term=term+1 WHERE doc=0"; 
    PreparedStatement updateQuey =con.prepareStatement(update);
    updateQuery.executeUpdate(update);
   }
   catch(Exception e)
   {
    e.printStackTrace();   
   }

但是我需要调用X,因为我想对多个列使用相同的行。 谢谢你提前

2 个答案:

答案 0 :(得分:0)

您可以使用带参数的预准备语句。来自oracle的here is the docu关于它。

在您的上下文中:

String update = "UPDATE test SET term = ? WHERE doc=0"; 
PreparedStatement updateQuey = con.prepareStatement(update);
updateQuey.setInt(1, x);
updateQuery.executeUpdate();

BTW:我认为您不需要更新字符串作为executeUpdate()

的参数

答案 1 :(得分:0)

如果您具体说明语句

 String update = "UPDATE test SET term=" + yourVariable + " WHERE doc=0"; 

但总是更喜欢使用预处理语句over语句来避免sql注入,这会使您的应用程序/软件更可靠,更不容易受到攻击。有关准备声明,请参阅luksch发布的答案