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;
}
}
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦