Trouble inserting data in a SQLite databae
public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\tim\\airline\\flightschedule.db");
PreparedStatement statement = connection.prepareStatement("INSERT INTO flights (flightID,departure,arrival)VALUES(?,?,?)");
statement.setInt(1,5);
statement.setString(2,"David");
statement.setString(3,"Ortiz");
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
开发者_Python百科 connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You should call a different method.
First things first though:
Bad code (wide open to SQL Injection attack):
statement = connection.createStatement();
resultSet = statement.executeQuery(
"INSERT INTO flights
('flightID','departure','arrival')
VALUES('"+flightID+"','"+departure+"','"+arrival+"')");
Good code:
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO flights (flightID,departure,arrival)
VALUES(?,?,?)");
statement.setString(1,flightID);
statement.setString(2,departure);
statement.setString(3,arrival);
statement.executeUpdate();
// thanks to @lobster1234 for reminder!
connection.commit();
Have you noticed I do executeUpdate() instead of executeQuery()? Because this is the cause of your trouble.
P.S. I also noticed that you pass flightID into the method as int, but insert it into database as a string. Not a good practice usually. Stick to one datatype. If ID is really a number, make it a number in the database and then call setInt(1,flightID); alternatively, pass it around as String too.
Try calling connection.commit()
after executeUpdate()
. You can also get the value returned by executeUpdate()
and make sure you get 1 and not 0, as this call returns the number of rows affected by the statement.
精彩评论