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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值