尝试执行 PreparedStatement 时出现 MySQLSyntaxErrorException [英] MySQLSyntaxErrorException when trying to execute PreparedStatement

查看:32
本文介绍了尝试执行 PreparedStatement 时出现 MySQLSyntaxErrorException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下方法使用 JDBC 的 PreparedStatement 插入一个 userId (int) 和一个 userName(String):

I tried to insert a userId (int) and a userName(String) using the PreparedStatement using JDBC using the following method:

public boolean saveUser(int userId, String userName){
    boolean saveStatus = false;
    try {
        connection.setAutoCommit(true);
        String sql = "insert into testtable values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        statement.setString(2, userName);
        saveStatus  = statement.execute(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally{
        Connector.closeConnections();
    }
    return saveStatus;
}

我得到以下堆栈跟踪:

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 '?,?)' at line 1

我做错了什么?

推荐答案

试试这个应该可行:

    try {
        connection.setAutoCommit(true);
        String sql = "insert into testtable values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        statement.setString(2, userName);
        saveStatus  = statement.execute();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return saveStatus;
}

PreparedStatement 是预编译语句.您不必在执行时提供 sql 字符串.

PreparedStatement is precompiled statement. you don't have to supply the sql string while executing.

这篇关于尝试执行 PreparedStatement 时出现 MySQLSyntaxErrorException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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