继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

Curtis_yang
关注TA
已关注
手记 63
粉丝 62
获赞 1091
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;
    }

}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP

热门评论

key 需要自己认证后获取

查看全部评论