java 读取12306最新火车站信息并存储
public static void getStation() {
// 声明Connection对象
Connection con;
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名 test
String url = "jdbc:mysql://localhost:3306/ar_dev?serverTimezone=UTC";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123";
try {
// 加载驱动程序
Class.forName(driver);
// 1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed())
System.out.println("\n\t\t成功以 " + user + " 身份连接到数据库!!!");
String sql = "INSERT ar_station(station_name,station_code,py_full,py_math,index_no) values(?, ?, ?, ?, ?)";
java.sql.PreparedStatement ptmt = null;
con.setAutoCommit(false);// 关闭事务
ptmt = con.prepareStatement(sql);
String url= "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js";
String result;
try {
result = HttpHelper.executeGet(url, "utf-8", 2000).getContent();
int startIdx = result.indexOf("'");
int endIdx = result.length()-2;
String city = result.substring(startIdx, endIdx);
String[] c = city.split("@");
// 遍历查询结果集
for (int i = 1; i < c.length; i++) {
String[] cc = c[i].split("\\|");
ptmt.setString(1, cc[1]);
ptmt.setString(2, cc[2]);
ptmt.setString(3, cc[3]);
ptmt.setString(4, cc[4]);
ptmt.setInt(5, Integer.parseInt(cc[5]));
ptmt.addBatch();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
ptmt.executeBatch();//执行给定的SQL语句,该语句可能返回多个结果
con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// 数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
// 数据库连接失败异常处理
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
System.out.println("\t\t\t\t\t\t\t\t获取数据库数据完毕!!!!!");
}
}