java每10秒打印_我的第五个java程序 每过10秒读取一次天气 并把天气更新到mysql...

我的第五个java程序 每过10秒读取一次天气 并把天气更新到mysql

我的第五个java程序 每过10秒读取一次天气 并把天气更新到mysql数据库里

a45780c35920fed2b46abd3c7b61e6f6.png

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("

(.+?)

");

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

}

}

}

我的第五个java程序 每过10秒读取一次天气 并把天气更新到mysql相关教程

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值