从Java ArrayList插入SQLite:需要插入多行
我试图使用for循环从ArrayList向SQLite数据库中插入行,但在数据库中只得到一行,而不是预期的多行 请参阅下面的代码段。为什么我的代码只插入一行从Java ArrayList插入SQLite:需要插入多行,java,sqlite,for-loop,arraylist,Java,Sqlite,For Loop,Arraylist,我试图使用for循环从ArrayList向SQLite数据库中插入行,但在数据库中只得到一行,而不是预期的多行 请参阅下面的代码段。为什么我的代码只插入一行 public class DbConnection { private static Connection conn; public static Connection Connector() { try { Class.forName("org.sqlite.JDBC");
public class DbConnection {
private static Connection conn;
public static Connection Connector() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:myDB.sqlite");
return conn;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public class Upload {
public boolean setUpload(String eID, String rID, String cID, int res, int point) throws SQLException{
connection = DbConnection.Connector();
PreparedStatement preparedStatement =null;
String query = "Insert into Result (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?)";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, eID);
preparedStatement.setString(2, rID);
preparedStatement.setString(3, cID);
preparedStatement.setInt(4, res);
preparedStatement.setInt(5, point);
preparedStatement.executeUpdate();
connection.commit();
return true;
} catch (Exception e) {
return false;
} finally {
preparedStatement.close();
}
}
//note ArrayList: "getList()" is sitting in another class.
public void update() throws SQLException {
for (int i=0; i<select.getSetUp().getList().size(); i++){
setUpload(select.getSetUp().getEID(),
select.getSetUp().getR().getId(),
select.getSetUp().getList().get(i).getId(),
select.getSetUp().getList().get(i).getRes(),
select.getSetUp().getList().get(i).getPoint());
}
}
}
公共类数据库连接{
专用静态连接连接器;
公共静态连接连接器(){
试一试{
Class.forName(“org.sqlite.JDBC”);
conn=DriverManager.getConnection(“jdbc:sqlite:myDB.sqlite”);
返回连接;
}捕获(例外e){
系统输出打印ln(e);
返回null;
}
}
公共类上载{
公共布尔setUpload(字符串eID、字符串rID、字符串cID、int res、int point)引发SQLException{
connection=DbConnection.Connector();
PreparedStatement PreparedStatement=null;
String query=“插入结果(col1、col2、col3、col4、col5)值(?、、?、?、?)”;
试试{
preparedStatement=connection.prepareStatement(查询);
准备好的报表。集合字符串(1,eID);
编制报表。设置字符串(2,rID);
编制报表。设置字符串(3,cID);
编制的报表。setInt(4,res);
编制报表。setInt(5分);
preparedStatement.executeUpdate();
commit();
返回true;
}捕获(例外e){
返回false;
}最后{
preparedStatement.close();
}
}
//注意ArrayList:“getList()”位于另一个类中。
public void update()引发SQLException{
对于(int i=0;该循环似乎正常。catch(Exception e){return false;}
不是一个好的做法。可能在循环中发生异常?尝试在Yossi的catch
+1中添加e.printStackTrace()
,如果您可以将列表本身传递给setUpload()
您可以使该循环迭代(ps.set…,executeUpdate.execute…)这样你将使用1个连接…只是一个建议谢谢Yossi。你完全正确。像个白痴一样,我忘记了我将eID作为主键。主键约束似乎是个问题。我现在将尝试重新运行。谢谢Yazan,是的,这看起来更合理。它正在工作。经典的我:总是一些愚蠢的事情。