dStatement时出现MySQLSyntaxErrorExc

dStatement时出现MySQLSyntaxErrorExc

本文介绍了尝试执行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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 21:50