只是我的尝试
我修改了代码并使用 List 获得了解决方案来保存 ResultSet 中的值,但我只有一个问题,即我无法在 Callable 中将结果作为类型 (ResultSet)
当我尝试使用未来的 get() 函数检索值时,结果集以某种方式为空
结果集 rs = (ResultSet)future.get();
下面是一段不起作用的代码,
ExecutorService service=Executors.newFixedThreadPool(1);
Callable<ResultSet> callable = new SelectThreadResultSet();
Future<ResultSet> future = service.submit(callable);
ResultSet rs = (ResultSet)future.get();
// Here I dont get any values
while(rs.next()){
System.out.println(rs.getString("EMPLOYEE"));
}
请在下面找到对我有用的解决方案,我使用 List 来保存值并返回它。
类选择线程类:
public class SelectThreadClass implements Callable<List<String>> {
public List<String> call(){
ResultSet rs = null;
List<String> strList = new ArrayList<String>();
try {
rs = perform();
while(rs.next()){
strList.add(rs.getString("EMPNAME"));
}
System.out.println("Passed");
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return strList;
}
public ResultSet perform() throws InstantiationException, IllegalAccessException, SQLException{
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
try {
conn = DriverManager.getConnection("jdbc:sqlite:C:\\SqlLite\\EMPLOYEE.db");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement s = null;
try {
s = conn.createStatement();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = null;
try {
rs = s.executeQuery(Utils.selectQuery);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}catch (ClassNotFoundException e){
e.printStackTrace();
return null;
}
}
}
类实用程序:
public class Utils {
public static String selectQuery = "SELECT EMPNAME FROM EMPLOYEEDETAILS";
public static void dbSelect(String query) throws InterruptedException, ExecutionException, SQLException{
ExecutorService service=Executors.newFixedThreadPool(1);
Callable<List<String>> callable = new SelectThreadClass();
Future<List<String>> future = service.submit(callable);
List<String> empList = future.get();
for(String emp : empList){
System.out.println(emp);
}
}
public static void main(String args[]) throws InterruptedException, ExecutionException, SQLException{
dbSelect("SELECT EMPNAME FROM EMPLOYEEDETAILS");
}
}