我参与Java项目并编写SQLite" Actionhandler-Class"您可以在这些表中创建/删除表并添加/更新/获取/删除条目。
表的一般创建/删除和添加条目工作正常,但现在我想创建getEntry(...)
函数。
public void getEntry(String table, String[] ident){
try{
stmt = conn.createStatement();
String exec = "SELECT " + ident[0] + " FROM " + table;
if(!ident[1].isEmpty()){
exec += " WHERE(" + ident[1] + ");";
}else{
exec += ";";
}
ResultSet res = stmt.executeQuery(exec);
while(res.next()){
System.out.println(res.getInt("uid"));
System.out.println(res.getString("uname"));
System.out.println(res.getString("pwd"));
System.out.println(res.getString("mail"));
System.out.println(res.getInt("rank"));
System.out.println(res.getInt("coins"));
System.out.println(res.getString("stg"));
}
res.close();
stmt.close();
}catch(Exception e){
e.printStackTrace();
}
}
这当然有效!
但我不希望System.out.println(...)
所有数据,我想将其返回给调用main(...)
函数的getEntry(...)
函数,以便它可以使用此数据。如何提供此函数的res
数据?
答案 0 :(得分:1)
您可以将该功能改为ResultSet
:
public ResultSet getEntry(String table, String[] ident){
try{
stmt = conn.createStatement();
String exec = "SELECT " + ident[0] + " FROM " + table;
if(!ident[1].isEmpty()){
exec += " WHERE(" + ident[1] + ");";
}else{
exec += ";";
}
ResultSet res = stmt.executeQuery(exec);
/* while(res.next()){
System.out.println(res.getInt("uid"));
System.out.println(res.getString("uname"));
System.out.println(res.getString("pwd"));
System.out.println(res.getString("mail"));
System.out.println(res.getInt("rank"));
System.out.println(res.getInt("coins"));
System.out.println(res.getString("stg"));
}res.close();
stmt.close();*/
return res;
}catch(Exception e){
e.printStackTrace();
}
}
然后在main中,您可以处理ResultSet
public static void main (String args []){
YourClass yourInstance = new YourClass ();
ResultSet tempResultSet = yourInstance.getEntry();
while( tempResultSet .next() ){
System.out.println(res.getInt("uid"));
System.out.println(res.getString("uname"));
System.out.println(res.getString("pwd"));
System.out.println(res.getString("mail"));
System.out.println(res.getInt("rank"));
System.out.println(res.getInt("coins"));
System.out.println(res.getString("stg"));
}
yourInstance .stmt.close() ; // this is assuming stmt is public
yourInstance.tempResultSet.close()
}
如果有一个方法返回stmt
假设getStmt()
,那么请用yourInstance.getStmt().close()