从数据库java连续打印新数据

时间:2017-12-21 15:14:50

标签: java

我正在开发基于控制台的程序,用户可以在其中登录并与其他用户聊天。我希望我的程序能够连续运行代码并检查新消息。每条消息在数据库中都有唯一的ID。因此,如果已经打印了一条消息,那么它应该跳过该消息并等待新消息。但我的程序只是打印第一条消息。我也尝试过其他一些方法但是在这种情况下会运行无限循环并且它会一次又一次地连续打印相同的消息。有人可以帮我吗?我会非常感激的!

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 = "";
    int tempMsgID = 0;
    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");
        while(rs.next()) {
            int dbRecID = rs.getInt("reciever_id");
            if(dbRecID == user_id) {
                while(true) {
                    msg = rs.getString("message");
                    int dbSenID = rs.getInt("sender_id");
                    int msgID = rs.getInt("message_id");
                    if(tempMsgID == msgID) {
                        System.exit(0);
                    }
                    else {
                        ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
                        while(rs1.next()) {
                            int senID = rs1.getInt("id");
                            if(senID == dbSenID) {
                                senName = rs1.getString("name");
                            }
                        }
                        System.out.println(senName+" sent you a message: "+msg);
                    }
                    tempMsgID = msgID;
                }
            }
        }
    }
}
}

0 个答案:

没有答案