JAVA JDBC mySql Prepared statement Update query [duplicate]

杀马特。学长 韩版系。学妹 提交于 2021-02-05 07:45:06

问题


I am trying to execute the following code

package jdbclesson;

import java.sql.*;

public class PreparedQuery {

public static void main(String[] args) throws Exception
{
    String url              = "jdbc:mysql://localhost:3306/alien?useSSL=false";
    String uname            = "root";
    String pass             = "ma123";
    String query            = "UPDATE student SET username= ? where userid= ? ";
    PreparedStatement stmt  = null;


    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, uname, pass);
    stmt = con.prepareStatement(query);

    stmt.setString(1, "tina");
    stmt.setInt(2, 6);


    int rs = stmt.executeUpdate(query);

    System.out.println(rs);
    stmt.close();
    con.close();

}

}

but getting following errors

Exception in thread "main" 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 '? where userid=?' at line 1

My database has only 1 table student with 2 columns userid and username and 10 rows what m i missing


回答1:


Try:

int rs = stmt.executeUpdate();

Instead of:

int rs = stmt.executeUpdate(query);

executeUpdate() runs the query of the prepared statement, which is what you want. executeUpdate(query) runs the query passed to the method. You were getting the error because you were passing an SQL with errors (contains ?).




回答2:


Please try:

"UPDATE student SET username= ? ” + ” where userid= ?"; 

int rs=stmt.executeUpdate();


来源:https://stackoverflow.com/questions/54583896/java-jdbc-mysql-prepared-statement-update-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!