我需要从3个不同的表中检索数据。最初我在查询中使用“连接”来获得结果。 3个表中的一个由大数据组成,这使得我的程序运行速度非常慢。所以,我把查询分为两部分。 1)我的一个查询返回字符串列表,而另一个查询应该返回整数。
现在我的疑问是如何在我的查询中使用这个列表?
我已经尝试了以下代码,但它会引发异常..请在此建议我
1.Method1:返回一个列表
public ArrayList<String> custList()
{
ArrayList<String> customerList=new ArrayList<String>();
try {
Class.forName("org.postgresql.Driver");
conection=DriverManager.getConnection("","");
Statment =coonection.createstatement;
String CustomerInfo="select username, place from customer where customerID >=100
and customerID <=200";
ResultSet result1=statement.executeQuery(CustomerInfo);
while(result.next)
{
String cust=rs.getString(username);
customerList.add(cust);
}
}
//required catch exceptions
//close resultset,connection,statement
return customerList;
}
2.Method:2我需要在其他查询中使用此客户用户名。我尝试了以下但未成功的
public int useCount()
{
int count=0;
//Using a method of same class, assuming my class name is customer
ArrayList<String> custtDetails=customer.custList();
try {
Class.forName("org.postgresql.Driver");
conection=DriverManager.getConnection("","");
Statment =coonection.createstatement;
String C=custtDetails.get(count);
String CustomerInfo="select count(*) login from customerdetails
where custUsername=C"; // <-- I need to use my list of strings here
ResultSet result1=statement.executeQuery(CustomerInfo);
while(result.next)
{
String cust=rs.getString(username);
customerList.add(cust);
count++; // <--- I think my mistake goes here ! How to use my list now??
}
}
//required catch exceptions
//close resultset,connection,statement
return useCount;
}
}
请建议我!!
答案 0 :(得分:1)
创建一个包含实例变量的类(比如EID和ENAME)并编写setter和getter(假设类名是Employee)
public class Employee implements java.io.Serializable {
private Integer eid;
private String ename;
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
}
现在写一个班级(比如RetriveRecords)
public class RetriveRecords {
public ArrayList listMethod(){
ArrayList list = new ArrayList();
try {
//Standard JDBC Code
Statement stmt = con.createStatement();
String query = "select * from emp"; // Your own Query
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
Employee e = new Employee();
e.setEno(rs.getInt(eno);
e.setEName(rs.getString("ename");
list.add(e);
}
con.close();
}
catch(Exception e){
e.printStackTrace();
}
return list;
}
}
public class DisplayRecords {
public static void main(String[] args){
RetriveRecords rr = new RetriveRecords();
ArrayList a = rr.listMethod();
Iterator i = a.iterator();
while(i.hasNext()){
Employee e =(Employee) i.next();
System.out.println(e.getEno());
System.out.println(e.getName());
}
}
}
完成......实际上,要克服ResultSet对象的限制(即无法传输ResultSet对象)...... Hibernate ORM在内部使用相同的代码。