我有两个问题:
1)我如何在UPDATE查询中调用变量,因为我希望使用同一行来更新许多列。我在INSERT和SELECT中这样做了,但它在更新我使用的where时会导致错误:
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,因为我想将同一行用于多个列。提前感谢
发布于 2013-05-20 00:18:21
您可以使用带参数的预准备语句。来自甲骨文的here is the docu。
在您的上下文中:
String update = "UPDATE test SET term = ? WHERE doc=0";
PreparedStatement updateQuey = con.prepareStatement(update);
updateQuey.setInt(1, x);
updateQuery.executeUpdate();顺便说一句:我不认为你需要更新字符串作为executeUpdate()的参数
发布于 2013-05-20 00:45:38
如果您是具体关于语句,那么
String update = "UPDATE test SET term=" + yourVariable + " WHERE doc=0"; 但是总是喜欢预准备语句而不是语句,以避免sql注入,这会使你的应用程序/软件更可靠,更不容易受到攻击。For prepare statement refer luksch发布的回答
https://stackoverflow.com/questions/16636717
复制相似问题