JAVA JDBC mySql预准备语句更新查询 [英] JAVA JDBC mySql Prepared statement Update query

查看:102
本文介绍了JAVA JDBC mySql预准备语句更新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下代码

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();

}

}

但出现以下错误

线程主"中的异常 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您有一个 您的SQL语法错误;检查与您的手册相对应的手册 MySQL服务器版本附近使用正确的语法吗?在哪里 userid =?在第1行

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

我的数据库只有一名表生,有2列用户名和用户名,还有10行我缺少的行

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

推荐答案

尝试:

int rs = stmt.executeUpdate();

代替:

int rs = stmt.executeUpdate(query);

executeUpdate()运行所需语句的查询. executeUpdate(query)运行传递给该方法的查询.之所以收到此错误,是因为您传递的SQL带有错误(包含?).

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 ?).

这篇关于JAVA JDBC mySql预准备语句更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆