我在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


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

最佳答案

preparedStatement.execute(query);


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

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

preparedStatement.execute();

09-30 18:55