一、步驟說明
1.加載驅動
2.創建數據庫連接
3.創建語句對象
4.創建sql
5.執行sql返回執行結果
6.關閉數據庫資源
二、代碼實現
package com.sjsq.dao;
import java.sql.*;
/**
* Java中使用JDBC連接數據庫
* @author shuijianshiqing
* @date 2020/6/18 18:40
*/
public class DBUtil {
// JDBC Driver
static final String JDEC_DRIVER = "com.mysql.cj.jdbc.Driver";
// URL(注意Mysql8.0只後需要添加時區信息)
static final String DB_URL = "jdbc:mysql://localhost/demo?serverTimezone=UTC";
// 賬號
static final String USER = "root";
// 密碼
static final String PASS = "admin";
public static void main(String[] args){
// 定義Connection
Connection conn = null;
// 定義Statement
Statement stmt = null;
try{
// 1.加載驅動
Class.forName(JDEC_DRIVER);
System.out.println("連接數據庫");
// 2.創建數據庫連接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("創建Statement對象");
// 3.創建語句對象
// Statement對象用於將 SQL 語句發送到數據庫中,執行對數據庫的數據的檢索或者更新。
stmt = conn.createStatement();
// 4.創建sql
String sql;
sql = "select * from user";
// 5.處理執行結果,執行sql,將結果保存在rs裏面
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println("name:" + username);
System.out.println("password:" + password);
}
// 6.關閉資源
rs.close();
stmt.close();
conn.close();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null) {
stmt.close();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
System.out.println("數據庫已關閉");
}
}