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();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
您应该调用其他方法。
首先要注意的是:
错误的代码(对SQL注入攻击大范围开放):
statement = connection.createStatement();
resultSet = statement.executeQuery(
"INSERT INTO flights
('flightID','departure','arrival')
VALUES('"+flightID+"','"+departure+"','"+arrival+"')");
好代码:
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();
您是否注意到我执行executeUpdate()而不是executeQuery()?因为这是您麻烦的原因。
附言我还注意到,您将flightID作为int传递给方法,但将其作为字符串插入数据库。通常不是一个好习惯。坚持一种数据类型。如果ID确实是一个数字,请在数据库中使其成为一个数字,然后调用setInt(1,flightID);。或者,也将其作为String传递。