This question already has answers here:
PreparedStatement with list of parameters in a IN clause [duplicate]
                                
                                    (15个答案)
                                
                        
                                5年前关闭。
            
                    
我是“准备好的语句”的新手,不确定我要执行的操作是否合法。

 String updatequery = "Update articles SET Title = ? WHERE id IN ?";

    try{
        prestatement = connect.prepareStatement(updatequery);

        prestatement.setString(1, "Test");
        prestatement.setString(2,"(4,5,6)");


我收到以下错误:

Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in        your SQL syntax; check the manual that corresponds to your MySQL server version for the     right syntax to use near ''(4,5,6)'' at line 1


似乎setString()方法在查询中添加了引号,是否有一种方法可以避免使用此方法或另一种方法来完成我要执行的操作?

最佳答案

尝试这个:

final Collection<Integer> ids = Arrays.asList(4, 5, 6);

final StringBuilder updatequery = new StringBuilder("Update articles SET Title = ? WHERE id IN (");

for (int i = 0; i < ids.size(); i++) {
    updatequery.append("?,");
}

updatequery.deleteCharAt(updatequery.length() - 1);
updatequery.append(")");

System.out.println(updatequery);

prestatement.setString(1, "Test");
int i = 2;
for (final Integer id : ids) {
    prestatement.setInt(i ++, id);
}

关于java - Java PreparedStatement setString()在查询中添加引号(mysql jdbc),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22303085/

10-11 03:32