java 在 SQLite 数据库中插入数据时遇到问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5774713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trouble inserting data in a SQLite databae
提问by tim
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();
}
}
}
回答by Vladimir Dyuzhev
You should call a different method.
您应该调用不同的方法。
First things first though:
不过首先要注意的是:
Bad code (wide open to SQL Injection attack):
错误代码(对 SQL 注入攻击开放):
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.
你有没有注意到我用 executeUpdate() 而不是 executeQuery()?因为这是你麻烦的原因。
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.
PS我还注意到您将flightID作为int传递到方法中,但将其作为字符串插入到数据库中。通常不是一个好习惯。坚持一种数据类型。如果 ID 确实是一个数字,则在数据库中将其设为一个数字,然后调用 setInt(1,flightID); 或者,也将它作为字符串传递。
回答by lobster1234
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.
尝试connection.commit()
在 之后调用executeUpdate()
。您还可以获得由 返回的值executeUpdate()
并确保您获得 1 而不是 0,因为此调用返回受语句影响的行数。