显示java mysql中两个表的数据

时间:2017-12-20 14:29:21

标签: java mysql database jdbc

我想显示带有发件人姓名的邮件。外部while循环工作正常,但内部while循环存在一些问题。我已经尝试了很多但没有得到任何结果。谁能帮我?我非常感激。

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class Messages extends Login {
    static Scanner in = new Scanner(System.in);

public static void main(String args[]) throws Exception{
    boolean isLoggedin = login();

    String msg = "";
    String senName = "";

    if(isLoggedin) {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false", "root", "");
        Statement st = con.createStatement();
        Statement st1 = con.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM chat");
        ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
        while(rs.next()) {
            int dbRecID = rs.getInt("reciever_id");
            if(dbRecID == user_id) {
                msg = rs.getString("message");
                int dbSenID = rs.getInt("sender_id");
                while(rs1.next()) {
                    int senID = rs1.getInt("id");
                    if(senID == dbSenID) {
                        senName = rs1.getString("name");
                    }
                }
                System.out.println(senName+" sent you a message: "+msg);
            }
        }

    }
    else {
        System.out.print("Login Unsuccessful");
    }
}
}

输出

Ali Ahmed sent you a message: How are you?
Ali Ahmed sent you a message: Hi!

所需输出

Ali Ahmed sent you a message: How are you?
Hamza sent you a message: Hi!

1 个答案:

答案 0 :(得分:1)

问题来自两个嵌套的while循环。

查询ResultSet rs1 = st1.executeQuery("SELECT * FROM data");只执行一次。

第一次循环while(rs.next())时,您将获取rs1的全部内容,以检查发件人ID是否正确。

然后在while(rs.next())上的第二次迭代,因为已经提取rs1 while(rs1.next())将返回false

为了让您的代码正常工作,您应该移动第二个查询的执行以获得如下内容:

while(rs.next()) {
    ...
    ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
    while(rs1.next()) {
        ...
    }
    ...
}
  

但我认为只做一个SQL是一个更好的解决方案   请求加入两个表的数据并包括where   条件。