【发布时间】:2014-12-23 13:02:31
【问题描述】:
我编写此方法以从 java 中的 SQLite 表中获取结果。
public String[][] select(String query, String table) throws ClassNotFoundException, SQLException
{
Connection con;
Statement st;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:"+table);
con.setAutoCommit(false);
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String[][] result = new String[100][4];
int j = 0;
while ( rs.next() ) {
String name = rs.getString("fullname");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
result[j][0] = name; // line number 63
result[j][1] = username;
result[j][2] = password;
result[j][3] = email;
j++;
}
rs.close();
st.close();
con.close();
return result;
}
从我的主要方法中我实例化了这个方法:
try{
String[][] data = db.select("SELECT * FROM user", "fliplist.db"); // line number 37
System.out.println(data);
} catch (ClassNotFoundException | SQLException e){
System.out.println(e.getMessage());
}
这给了我这个错误:
run:
Exception in thread "main" java.lang.NullPointerException
at FlipList.Database.select(Database.java:63)
at FlipList.FlipList.main(FlipList.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
应该如何获取结果?
更新
我已经初始化了数组的第二维,现在它显示了这个错误(很可能是 garbez 值):
run:
[[Ljava.lang.String;@2077d4de
BUILD SUCCESSFUL (total time: 2 seconds)
我怎样才能返回一个数组?
【问题讨论】:
-
帮我们一个忙,并在导致错误的行上添加注释,这样我们就可以看到它在哪里,而不必猜测您没有显示多少代码。
-
谢谢,我在评论区插入了行号
-
您没有初始化数组的第二维,这就是它为空的原因。应该是
new String[100][4]。此外,在while循环之外增加行计数器j。 -
我不确定它是否会修复它,但我认为您必须在执行语句后添加
con.commit -
@lea 可能想把它放到答案中。