亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消