为什么我收到此sql错误?

时间:2014-08-02 13:25:25

标签: java mysql sql-insert sqlexception

我在NetBeans中启动了我的java代码,我想在数据库numbersdb中的firstdb表中插入一些数据。我在运行程序时遇到问题。

我的代码就是这个:

public static void main(String [] arg){
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded!");
        Connection dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/firstdb", "root","root");
        System.out.println("Connection to database succeded!");

        boolean evening = false;
        int n100 = 1;
        int n10 = 2;
        int n1 = 3;
        int wn = 123;
        int month = 0;
        int day = 0;
        int year = 0;
        java.sql.Date date_released = new java.sql.Date(Calendar.getInstance().getTime().getTime());

        String query =  "insert into numbersdb (hundreds_place, tens_place, ones_place, whole_number, evening, date_released, day, month, year) "+
                        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        PreparedStatement preparedStatement = dbc.prepareStatement(query);
        preparedStatement.setInt(1, n100);
        preparedStatement.setInt(2, n10);
        preparedStatement.setInt(3, n1);
        preparedStatement.setInt(4, wn);
        preparedStatement.setBoolean(5, evening);
        preparedStatement.setDate(6, date_released);
        preparedStatement.setInt(7, day);
        preparedStatement.setInt(8, month);
        preparedStatement.setInt(9, year);

        preparedStatement.execute(query);       

        System.out.println("Query executed!!!");

    } catch (SQLException ex) {
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Cannot find the driver in the classpath!", e);
    } 
}

我在phpmyadmin中用这个sql代码创建了我的数据库:

create table numbersdb (  
    hundreds_place int unsigned not null,  
    tens_place int unsigned not null,   
    ones_place int unsigned not null,   
    whole_number int unsigned not null,  
    evening boolean not null,  
    date_released date not null,  
    day int unsigned not null,  
    month int unsigned not null,  
    year int unsigned not null,  
    primary key (date_released)  
);

我的程序输出是这个:

  

驱动程序已加载!与数据库的连接成功! SQLException:您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'?,?,?,?,?,?,?,?,?)'在第1行SQLState:42000
  VendorError:1064

为什么我会收到此例外情况?

1 个答案:

答案 0 :(得分:3)

preparedStatement.execute(query);

此行使用从.execute(String)继承的Statement。所述方法仅执行现在包含?的给定查询。

删除参数以使用正确的方法,它将起作用。

preparedStatement.execute();