Java入门-获取MySQL数据
java代码
public class mysqlTest {
@Test
public void getMysqlCon(){
Connection con;
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/spider?serverTimezone=UTC";
String user = "root";
String password = "123456";
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed())
System.out.println("\n\t\t成功以 " + user + " 身份连接到数据库!!!");
Statement statement = con.createStatement();
String sql = "select * from data_db";
ResultSet rs = statement.executeQuery(sql);
System.out.println("\n\t\t执行结果如下所示:");
System.out.println("\t\t-----------------------------------------------------------------");
System.out.println("\t\t|\t" + "Id" + "\t" + "Url" + "\t" + "Title" + "\t" + "Date\t|");
System.out.println("\t\t-----------------------------------------------------------------");
Integer id = null;
String href = null;
String title = null;
String date = null;
while (rs.next()) {
id = rs.getInt("id");
href = rs.getString("url");
title = rs.getString("title");
date = rs.getString("date");
System.out.println("\t\t|\t" + id + "\t" + href + "\t" + title + "\t" + date+ "\t|\t\t");
}
System.out.println("\t\t-----------------------------------------------------------------");
rs.close();
con.close();
}
catch (ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
System.out.println("\t\t\t\t\t\t\t\t获取数据库数据完毕!!!");
}
}
}
结果
