每日日报2020 9/28

今天连接数据库,不能再拖了。按照菜鸟教程的东西来。

package pack;

import java.sql.*;
public class domo {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/course"+"?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "songzhenxing";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{

Class.forName(JDBC_DRIVER);


System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);


System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT teacher_id, teacher_name";
ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){
// 通过字段检索
int name = rs.getInt("teacher_name");
String id = rs.getString("teacher_id");


rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
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!");
}
}

posted @ 2020-09-28 22:19  宋振兴  阅读(48)  评论(0编辑  收藏  举报