Ant*_*hea 2 java database jdbc
我有以下结构:
列表 - > List_Participant - >参与者
所以列表可能包含几个参与者.我尝试在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();
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我没有收到异常或任何其他输出.我建议打开第二个结果集将关闭第一个结果集因为我做了第一个结果集,将数据存储在一个arraylist中并关闭它,然后第二个结果集将工作,但这会导致性能不佳,因为我必须始终搜索arraylist.
什么可能是更好的解决方案?
编辑:解决方案是进行加入,我当前尝试:
select * from List_participant
INNER JOIN List ON List.name = List_participant.List
INNER JOIN participant ON List_participant.participant =participant.ROWID;
Run Code Online (Sandbox Code Playgroud)
我现在如何处理列,因为它们可能具有相同的名称?
您可以尝试为每个查询使用两个不同的Statement实例.请参阅JavaDoc以获取java.sql.Statement.以下示例显示了原理.
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
}
}
Run Code Online (Sandbox Code Playgroud)
但是:出于好的原因,这不是JDBC或SQL的标准用法.它剥夺了数据库的任何优化可能性,并且没有充分理由在数据库和您的应用程序之间移动大量数据(参见JohnSkeet和BalusC的评论).
更好地使用适当的JOIN罪,你唯一的声明.这可以通过DB优化:
SELECT lp.* FROM list l JOIN List_Participant lp ON l.name = lp.name
Run Code Online (Sandbox Code Playgroud)
添加您喜欢的任何过滤器/条件,以最小化检索到的数据.