将 ArrayList<String> 添加到 SQLite DB



我正在编写我的第一个程序,并尝试使用JDBC驱动程序SQLite-JDBC-3.7.2.jar将ArrayList数据(从CSV数据库)传输到SQLite数据库。我已经阅读了SQLite和java初学者的教程,以及对stackoverflow(链接1、链接2)问题的不同回答,我终于可以创建一个包含表和变量列(数据类型:TEXT)的数据库了。但是,当我尝试使用以下方法将ArrayList中的记录添加到我的测试表中时:

/**
* Add record from ArrayList<string> to table
* @param selectTable (name of table)
* @param line (List with record for table)
*/
public void addRecord (String selectTable, ArrayList<String> line){
try{
//connect to database
connection = new DBconnect(pathDataBase);
database = connection.getConnection();
//create SQL Statement
ArrayList<String> columnNames = new ArrayList<String>();
columnNames = getColumnList(selectTable); //call method to get all columnNames from selected table
String sSQL = "INSERT INTO " + selectTable + "("; //update statement (string sSQL)
//disperse ArrayList<string> columnNames in parts to add to the statement(string sSQL)
int i = 0;
for (i=0; i<columnNames.size(); i++){
sSQL = sSQL + columnNames.get(i);
if (columnNames.size() + 1 > i+2){
sSQL = sSQL + ", "; //update statement(string sSQL)
}//end if
}// end for
sSQL = sSQL + ") VALUES("; //update statement(string sSQL)
//disperse ArrayList<string> line in parts to add to the statement(string sSQL)
i=0;
for (i=0; i<columnNames.size(); i++){
sSQL = sSQL + line.get(i); //add record per line in columns
if (columnNames.size() + 1 > i+2){
sSQL = sSQL + ", ";
}//end if
}//end for
sSQL = sSQL + ");";
System.out.println(sSQL);
Statement statement = database.createStatement();
System.out.println("created statement");
statement.executeUpdate(sSQL);
System.out.println("executed Update");
statement.close();
database.close();
//catch exception
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}//end try/catch
}//end method

我得到以下异常描述:

Opened database successfully
INSERT INTO Testtable(Test1, Test2, Test3) VALUES(Hallo1, Hallo2, Hallo3); //(ArrayList<string> columnNames) (ArrayList<string> line)
created statement
java.lang.NullPointerException: null

我认为我的字符串"sSQL"中一定有错误。

有人知道我必须改变什么才能让它发挥作用吗?我可以不在"Text"列中写入数据类型"string"吗?

我希望我能理解我的问题,并提出正确的问题。

非常感谢。:)

@哦,天哪,我被自己的愚蠢绊倒了。我打开了一个到数据库的连接并调用了一个方法,该方法也打开了一条连接并关闭了它。当然,现在我不能执行语句,因为我的数据库已经关闭了。感谢Naren抽出时间!!!

使用这样的循环。。。如果你通过像Test0 Test1 Test2 Test3这样的输入,就会产生像这样的输出

Test0,Test1,Test2,Test3

所以

for(int i=0;i<columnNames.size();i++)
{
str=str+columnNames.get(i);
if(!(i+1==columnNames.size()))
{
str=str+",";
}
}

第二个用于环路

for (i=0; i<line.size(); i++){
sSQL = sSQL + line.get(i); //add record per line in columns
if(!(i+1==line.size()))
{
str=str+",";
}
}

以及在构建时在查询中插入"?"(占位符)。。如果是这样的话,你应该使用PreparaedStatement ps和类似ps.setInt()的方法来填充其中的正确值,然后你应该执行Update()。。。如果你想使用prepareStatement,你可以检查http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

最新更新