I started my java code in NetBeans, I wanted to insert some data in my numbersdb
table located in the database firstdb
. I'm having problems when I run the program.
My code is this one:
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);
}
}
I created my database with this sql code in phpmyadmin:
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)
);
The output of my program is this one:
Driver loaded! Connection to database succeded! SQLException: 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 SQLState: 42000
VendorError: 1064
Why am I getting this exceptions?
preparedStatement.execute(query);
This line uses .execute(String)
inherited from Statement
. Said method only executes the given query that now contains the ?
's.
Remove the argument to use the correct method and it'll work.
preparedStatement.execute();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.