import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Arrays; import java.sql.*; import java.util.Timer; import java.io.IOException; public class Weather { String urlString; String array; String tianqi; StringBuffer sb=new StringBuffer(""); public static void main(String[] args) throws Exception { Timer timer = new Timer(); timer.schedule(new MyTask(), 1000, 10000); while (true) { try { int ch = System.in.read(); if (ch - 'c' == 0) { timer.cancel(); } } catch (IOException e) { e.printStackTrace(); } } } static class MyTask extends java.util.TimerTask { @Override public void run() { // TODO Auto-generated method stub Weather client = new Weather("http://www.weather.com.cn/weather/101181201.shtml"); try { client.run(); }catch(Exception e) { e.printStackTrace(); } } } public Weather(String urlString) { this.urlString = urlString; } public void run() throws Exception { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection .getInputStream(),"utf8")); String line; while ((line = reader.readLine()) != null){ Pattern p = Pattern.compile("<p class="wea">(.+?)</p>"); Matcher m = p.matcher(line); while(m.find()) { array = m.group(1); sb.append(array+","); } } String arr = sb.toString(); String[] s = arr.split("\,"); tianqi=s[s.length - 7]; String driver = "com.mysql.jdbc.Driver"; String urls = "jdbc:mysql://127.0.0.1:3306/scutcs"; String user = "root"; String password = "root"; try { Class.forName(driver); Connection conn = DriverManager.getConnection(urls, user, password); if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); Statement statement = conn.createStatement(); String sql = "UPDATE `scutcs`.`student` SET `SNAME` = '"+tianqi+"' WHERE `student`.`SNO` = '2';"; System.out.println(sql); //ResultSet rs = statement.executeQuery(sql); statement.executeUpdate(sql); //rs.close(); conn.close(); } catch(ClassNotFoundException e) { System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } }