将数据插入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();
}
}
}
您应该调用其他方法。
首先第一件事情,但:
错误代码(全方位开放的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()?因为这是你麻烦的原因。
P.S.我还注意到,您将flightID作为int传入方法,但将其作为字符串插入到数据库中。通常不是一个好习惯。坚持一种数据类型。如果ID实际上是一个数字,则将其作为数据库中的一个数字,然后调用setInt(1,flightID);或者,也可以像String一样传递它。
尝试在executeUpdate()
之后致电connection.commit()
。您还可以获得executeUpdate()
返回的值,并确保得到1而不是0,因为此调用返回受该语句影响的行数。
hehe ...现在我想知道在将commit()添加到...之后,将INSERT传递给query()的原始版本是否也能与SQLite一起工作... – 2011-04-25 03:30:29
我听到你!我被Spring-JDBC宠坏了,你不必处理样板代码太多:) – lobster1234 2011-04-25 03:33:09
你能粘贴你看到的异常跟踪吗? – lobster1234 2011-04-25 02:40:27
我没有看到任何 – tim 2011-04-25 02:45:45