完全参考菜鸟教程,做了点必要的修改。
package school_databases;
import java.sql.*;
public class ConnectToMysql {
static final String JDBC_DRIVER="com.mysql.cj.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/university?useSSL=false&serverTimezone=UTC";
static final String user="root";
static final String PASS="******";
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("连接数据库...");
conn=DriverManager.getConnection(DB_URL,user,PASS);
System.out.println("实例化Statement对象...");
stmt=conn.createStatement();
String sql;
sql="SELECT schoolName,city FROM SCHOOL LIMIT 10";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
String school=rs.getString("schoolName");
String city=rs.getString("city");
System.out.printf("school:%-20s",school);
System.out.println("city:"+city);
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(stmt!=null) stmt.close();
}catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
}catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}