在 SQLite 数据库中插入数据时遇到问题
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();
}
}
}
你应该调用不同的方法.
You should call a different method.
首先要做的是:
错误代码(对 SQL 注入攻击开放):
Bad code (wide open to SQL Injection attack):
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()?因为这是你麻烦的原因.
Have you noticed I do executeUpdate() instead of executeQuery()? Because this is the cause of your trouble.
附言我还注意到您将 flightID 作为 int 传递到方法中,但将其作为字符串插入到数据库中.通常不是一个好习惯.坚持一种数据类型.如果 ID 确实是一个数字,则在数据库中将其设为一个数字,然后调用 setInt(1,flightID);或者,也将其作为字符串传递.
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.