为了账号安全,请及时绑定邮箱和手机立即绑定

java 聚合数据 天气 API接口调用

标签:
Java
public class GetDataIntoTable {

    public static void main(String[] args) throws Exception {
        Connection conn = DatabaseConnection.getConnection();
        String cityName = "广州";
        if (getByCityName(cityName)) {
            PreparedStatement pstmt = conn.prepareStatement("SELECT city,message FROM tianqi WHERE city=?");
            pstmt.setString(1, cityName);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                System.out.print(rs.getString(2));
            }
        } else {
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO tianqi(city,message,modify) VALUES(?,?,?)");
            String msg = getData(cityName);
            pstmt.setString(1, cityName);
            pstmt.setString(2, msg);
            pstmt.setTimestamp(3, new Timestamp(new java.util.Date().getTime()));
            pstmt.executeUpdate();
        }
    }

    public static String getData(String cityName) throws Exception {
        String city = URLEncoder.encode(cityName, "UTF-8");
        URLConnection conn = new URL(
                "http://v.juhe.cn/weather/index?format=2&cityname=" + city + "&key=e643d606ab8b9b5636dcc02368")
                        .openConnection();
        conn.connect();
        InputStream input = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        return reader.readLine();
    }

    public static boolean getByCityName(String city) throws Exception {
        Connection conn = DatabaseConnection.getConnection();
        PreparedStatement pstmt = conn.prepareStatement("SELECT COUNT(*) FROM tianqi WHERE city=?");
        pstmt.setString(1, city);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            if (rs.getInt(1) > 0) {
                return true;
            }
        }
        return false;
    }

}
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Python工程师
手记
粉丝
62
获赞与收藏
1091

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 1
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消