java jdbc 查询多结果,java jdbc访问多个结果集

I have the following structure:

List -->List_Participant -->Participant

so a list may contain several participants.I try to read this in java:

stat = con.createStatement();

ResultSet rs = stat.executeQuery("select * from list;");

// get the informations about the bracket sheet

while (rs.next()) {

string name = rs.getString("Name");

ResultSet rs2 = stat.executeQuery("select * from List_Participant where name= '"+name+"';");

while (rs2.next()) {

// get the participants

}

rs2.close();

}

rs.close();

But this does not work. I don't receive an exception nor any other output. I suggest opening a second resultset will close the first one because since I do the first resultset, store the data in an arraylist and close it and afterwards the second it would work, but that leads to a poor performance because I have to search always in the arraylist.

What might be a better solution?

Edit: Solution is to make a Join, my current try:

select * from List_participant

INNER JOIN List ON List.name = List_participant.List

INNER JOIN participant ON List_participant.participant =participant.ROWID;

How do I adress the columns now, since they might have the same name?

解决方案

You can try using two different Statement instances for each query. See the JavaDoc for java.sql.Statement. The following example shows the principle.

Statement statement1 = connection.createStatement();

Statement statement2 = connection.createStatement();

ResultSet resultSet1 = statement1.executeQuery("select * from list");

while(resultSet1.next()){

String name = resultSet1.getString("Name");

ResultSet resultSet2 = statement2.executeQuery("select * from List_Participant where name= '"+name+"'");

while(resultSet2.next()){

// get the participants

}

}

BUT: This is not standard usage of JDBC or SQL for good reasons. It deprives the database of any optimization possibility and moves to much data between the DB and your app for no good reason (See the comments of JohnSkeet and BalusC).

Better use appropriate JOINsin your one and only statement. This can be optimized by the DB:

SELECT lp.* FROM list l JOIN List_Participant lp ON l.name = lp.name

Add any filters/conditions you like to minimize the data retrieved.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值