[英]Using Java, what is the best way to update a column in every row with values from an array? (SQLite)
Today is my first day using SQLite. 今天是我使用SQLite的第一天。 I am using Java to interact with an SQLite database that contains fields called ID, NAME, CITY. 我正在使用Java与包含名为ID,NAME,CITY的字段的SQLite数据库进行交互。 I would like to take every record in the database and replace the CITY field with a value from an array. 我想获取数据库中的每条记录,并用数组中的值替换CITY字段。 Here is what I tried, but realized right away it was wrong. 这是我尝试过的方法,但立即意识到这是错误的。 I believe the query is replacing every record 3 times which gives the result that each CITY field is 'Compton'. 我相信该查询正在替换每条记录3次,这使得每个CITY字段均为“ Compton”。 I am not sure on what is a good or efficient way to do this. 我不确定执行此操作的最佳方法是什么。
public void update(String cities[]) throws SQLException {
PreparedStatement updateCity = null;
Connection con = null;
String updateString = "update SUPPLIERS set CITY = ?";
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:suppliers.db);
con.setAutoCommit(false);
updateCity = con.prepareStatement(updateString);
for (int i = 0; i < cities.length; i++) {
updateCity.setString(1, cities[i]);
updateCity.executeUpdate();
con.commit();
}
} catch (Exception e) {
e.printStackTrace();
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch (SQLException excep) {
excep.printStackTrace();
}
}
} finally {
if (updateCity != null) {
updateCity.close();
}
con.setAutoCommit(true);
con.close();
}
}
I was calling the method like so instance.update(new String[]{"san diego", "los angeles", "Compton"});
我正在像这样调用方法instance.update(new String[]{"san diego", "los angeles", "Compton"});
. 。 I would like to know how to go about doing this with a PreparedStatement if possible, but if this is not the best way to go, please post an alternative suggestion. 如果可能的话,我想知道如何使用PreparedStatement进行此操作,但是如果这不是最好的方法,请发表替代建议。
Note: This is not my code, it is code taken from SQLite Java Tutorials . 注意:这不是我的代码,它是从SQLite Java Tutorials中获取的代码。
Your update statement will update ever record in the table each time it is called. 您的更新语句将在每次被调用时更新表中的记录。 If you want the statement to update only one record at a time, you will need to change your update statement to something like this: 如果您希望该语句一次仅更新一条记录,则需要将您的update语句更改为以下内容:
update SUPPLIERS set CITY = ? where ID = ?
If you want to update all records, you'll need to execute a query to get all of the IDs. 如果要更新所有记录,则需要执行查询以获取所有ID。 A query like this should work: 这样的查询应该工作:
select ID from SUPPLIERS
Then for each ID returned, call the update statement using that ID and whatever city you wish to update the record with. 然后对于返回的每个ID,使用该ID以及您希望用来更新记录的任何城市,调用更新语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.