Java監聽mysql數據表變化是一種常用的做法,可以在數據表發生變化時快速及時地進行處理。下面是一個簡單的示例:
public class MySQLWatcher implements Runnable{
private Connection conn;
private Statement stmt;
private ResultSet rs;
private String dburl;
private String dbuser;
private String dbpwd;
private String tablename;
private int interval;
public MySQLWatcher(String dburl, String dbuser, String dbpwd, String tablename, int interval) {
this.dburl = dburl;
this.dbuser = dbuser;
this.dbpwd = dbpwd;
this.tablename = tablename;
this.interval = interval;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dburl, dbuser, dbpwd);
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
rs = stmt.executeQuery("SELECT * FROM " + tablename);
while (rs.next()) {
//處理數據表的變化
}
Thread.sleep(interval);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String dburl = "jdbc:mysql://localhost:3306/test";
String dbuser = "root";
String dbpwd = "password";
String tablename = "mytable";
int interval = 5000;
MySQLWatcher watcher = new MySQLWatcher(dburl, dbuser, dbpwd, tablename, interval);
Thread thread = new Thread(watcher);
thread.start();
}
}
上面的代碼中,我們建立了一個MySQLWatcher類來監聽指定的數據庫表的變化。在實例化該類的時候,我們需要傳入四個參數:
dburl:指向要監聽的數據庫的URL
dbuser:數據庫所需的用戶名
dbpwd:數據庫所需的密碼
tablename:要監聽的數據表名
interval:輪詢時間間隔
在MySQLWatcher類的run()方法中,我們使用了一個while循環來不斷的輪詢數據表的變化。當數據表發生變化的時候,我們可以在while(rs.next())代碼塊中進行數據處理的操作。
最后,我們在main方法中創建MySQLWatcher實例,并使用Thread來啟動監聽線程。