java定时器访问db2数据库

package diaodu;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

    public static String driver = "com.ibm.db2.jcc.DB2Driver";
    public static String url = "jdbc:db2://localhost:50000/gold0923";
    public static String userid = "zhanglichao";
    public static String password = "000000";

    public static void main(String[] args) throws Exception {

        String sql = " select count(*) from zhanglichao.payment";
        Timer timer = new Timer();
        MyTask mt = new MyTask();
        mt.setConn(getConnection());
        mt.setSql(sql);
        timer.schedule(mt, 1000, 2000);//

        while (true) {
            int ch = System.in.read();
            boolean flag = true;
            if (ch == 13 && flag) {
                System.err.println("关闭定时器 ?(y)");
            }
            if (ch - 'y' == 0) {//输入y关闭定时器,关闭连接,退出程序
                closeConn(mt);
                timer.cancel();
                flag = false;
                System.exit(0);
            }
        }
    }

    public static void closeConn(MyTask mt) {
        try {
            mt.getConn().close();
            System.out.println("连接已关闭");
        } catch (SQLException e) {
            throw new RuntimeException("关闭异常", e);
        }
    }

    public static void selectOper(Connection conn, String sql) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                System.out.println("表中有数据" + rs.getInt(1) + "条");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = (Connection) DriverManager.getConnection(url, userid, password);

        } catch (Exception e) {
            throw new RuntimeException("连接异常", e);
        }
        return conn;
    }
}

class MyTask extends TimerTask {
    private Connection conn = null;
    private String sql = null;

    public void setSql(String sql) {
        this.sql = sql;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    @Override
    public void run() {
        TimerTest.selectOper(conn, sql);
    }
}

 

你可能感兴趣的:(java,sql,jdbc,db2,IBM)