【发布时间】:2014-02-14 12:52:31
【问题描述】:
我正在编写我的第一个程序并尝试使用 JDBC 驱动程序 sqlite-jdbc-3.7.2.jar 将带有 ArrayList(来自 CSV 数据库)的数据传输到 SQLite 数据库。 我已经阅读了tutorials für SQLite 和 java 初学者以及对 stackoverflow 问题的不同答案(Link 1,Link 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”中的某些内容一定是错误的。
有人知道我必须改变什么才能让它工作吗? 我不能在“文本”列中写入数据类型“字符串”吗?
我希望我可以理解地描述我的问题并提出正确的问题。
提前非常感谢。 :)
@all:哦,伙计,我因自己的愚蠢而跌跌撞撞。我打开了一个到数据库的连接并调用了一个方法,该方法也打开了一个连接并关闭了它。当然现在我不能执行语句,因为我的数据库已关闭。谢谢你的时间!
【问题讨论】: