JDBC从Select ResultSet中选择

时间:2013-11-17 12:20:15

标签: java sql select jdbc

这是我的表格:

table Paciente
+------------------------------------+
|   Nome   |   RG   |   ID_Paciente  |
+------------------------------------+
|  Lucas   |  10101 |        1       |
+------------------------------------+

table Telefone
+---------------------------------------------------------+
|  DDD   |   Telefone   |   ID_Paciente  |   ID_Telefone  |
+---------------------------------------------------------+
|   41   |   123456789  |        1       |       1        |
+---------------------------------------------------------+

我需要从Telefone表中打印DDD和Telefone。

我正在尝试做这样的事情:

String sql = "select ID_Paciente from Paciente where Nome = '"+nome+"'";
PreparedStatement st = c.getConnection().prepareStatement(sql);

ResultSet res = st.executeQuery();

sql = "select DDD from Telefone where ID_Paciente = '"+res.getString(1)+"'";
st = c.getConnection().prepareStatement(sql);

res = st.executeQuery();

while(res.next())
{   
      System.out.println("  DDD: "+res.getString(1));
}

但是,它不起作用

一些帮助?

3 个答案:

答案 0 :(得分:0)

您可以使用join而不是2次执行查询

SELECT Telefone.DDD, Telefone.Telefone, 
FROM Telefone
INNER JOIN Paciente
ON Telefone.ID_Paciente=Paciente.ID_Paciente;


String sql = "SELECT Telefone.DDD, Telefone.Telefone, 
    FROM Telefone
    INNER JOIN Paciente
    ON Telefone.ID_Paciente=Paciente.ID_Paciente where Paciente.Nome=?";
PreparedStatement st = c.getConnection().prepareStatement(sql);
st.setString(1,nome);
ResultSet res = st.executeQuery();
while(res.next())
{
//your code to retrieve
}

答案 1 :(得分:0)

虽然我可以回答你的问题,但我认为分开发布两个选择语句并不是一个好方法。您可以组合语句并触发一个查询:

"select DDD from Telefone where ID_Paciente in (select ID_Paciente from Paciente where Nome = '"+nome+"')"

答案 2 :(得分:0)

你需要类似的东西(未经测试):

final String sql = "SELECT t.DDD, t.Telefone FROM Telefone t" + 
                   " LEFT JOIN Paciente p ON (t.ID_Paciente = p.ID_Paciente)" + 
                   " WHERE p.Nome = ?";
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;

try {
    con = c.getConnection();
    stm = con.prepareStatement(sql);
    stm.setString(1, nome);

    rs = stm.executeQuery();

    while (rs.next()) {
        System.out.println(String.format("DDD = %d, Telefone = %s", 
            rs.getLong(1), rs.getString(2)));
    }
} catch (final SQLException e) {
    // TODO handle exception
    e.printStackTrace();
} finally {
    try {
        if (rs != null) {
            rs.close();
        }
        if (stm != null) {
            stm.close();
        }
        if (con != null) {
            con.close();
        }
    } catch (final SQLException e) {
        // ignore
    }
}