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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Vla*_*hev 10
你应该调用另一种方法.
首先要做的事情是:
错误的代码(对SQL注入攻击开放):
statement = connection.createStatement();
resultSet = statement.executeQuery(
"INSERT INTO flights
('flightID','departure','arrival')
VALUES('"+flightID+"','"+departure+"','"+arrival+"')");
Run Code Online (Sandbox Code Playgroud)
好代码:
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();
Run Code Online (Sandbox Code Playgroud)
您是否注意到我执行executeUpdate()而不是executeQuery()?因为这是你麻烦的原因.
PS我还注意到你将flightID作为int传递给方法,但是将其作为字符串插入数据库.通常不是一个好习惯.坚持一种数据类型.如果ID实际上是一个数字,请将其作为数据库中的数字,然后调用setInt(1,flightID); 或者,也将它作为String传递.
归档时间: |
|
查看次数: |
10025 次 |
最近记录: |