如何每2秒在数据库表中输出数据?

时间:2016-02-13 01:42:41

标签: java multithreading jdbc

我有一个名为LETTER的数据库表,并且有一列LETTER。它有一个从A到Z的字母数据。我希望它每2秒按顺序输出一次,如果它在文件的末尾,它会循环回到A.我的程序输出所有这些字母全部来自AZ。然后,它输出另一个随机字母,也一次输出。我希望它按顺序输出一个。我该如何解决?

import java.sql.*;
import java.util.Timer;
import java.util.TimerTask;
public class GUIThread {
    static Connection con; 
    static Statement stmt; 
    static ResultSet rs;
    int curRow = 0;

    public static void DoConnect(){
        try{
            String host = "jdbc:derby://localhost:1527/Mariel";
            String uName = "mariel";
            String uPass = "1234";
            con = DriverManager.getConnection(host, uName, uPass);

            stmt = con.createStatement();
            String SQL = "SELECT * FROM LETTER";
            rs = stmt.executeQuery(SQL);

            while(rs.next()){
                final String letter;
                letter = rs.getString("LETTER");
                class SayHello extends TimerTask {
                    public void run() {
                        System.out.println(letter);
                    }
                }
                Timer timer = new Timer();
                timer.schedule(new SayHello(), 0, 2000);
            }
        }
        catch(SQLException err){
            System.out.println(err.getMessage());
        }
    }

    public static void main(String args[]){
        DoConnect();
    }
}

这是我的程序的输出,我不希望它是这样的:here

1 个答案:

答案 0 :(得分:0)

我设法解决了它

public class GUIThread {
    static Connection con; 
    static Statement stmt; 
    static ResultSet rs;
    int curRow = 0;

    public static void DoConnect(){
        try{
            String host = "jdbc:derby://localhost:1527/Mariel";
            String uName = "mariel";
            String uPass = "1234";
            con = DriverManager.getConnection(host, uName, uPass);

            stmt = con.createStatement();
            String SQL = "SELECT * FROM LETTER";
            rs = stmt.executeQuery(SQL);

            class printLetter extends TimerTask {
                @Override
                public void run() {
                    try {
                        rs.next();
                        final String letter;
                        letter = rs.getString("LETTER");
                        System.out.println(letter);
                    } catch (SQLException ex) {
                        DoConnect();
                    }
                }
            }
            Timer timer = new Timer();
            timer.schedule(new printLetter(), 0, 2000);
        }
        catch(SQLException err){
            System.out.println(err.getMessage());
        }
    }

    public static void main(String args[]){
        DoConnect();
    }
}