1.數據庫連接管理
1.1 使用JDBC獲取連接
JDBC是Java標準庫提供的API,用于連接和操作關系型數據庫。它是最基礎、最常用的數據庫連接方式。
步驟:
- 加載數據庫驅動。
- 建立連接。
- 創建Statement或PreparedStatement對象。
- 執行SQL查詢或更新。
- 處理結果集。
- 關閉連接。
private static final String URL = "jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC";private static final String USER = "root";private static final String PASSWORD = "226774";public static void main(String[] args) {Connection connection = null;PreparedStatement preparedStatement = null;ResultSet resultSet = null;try {// 1. 加載數據庫驅動Class.forName("com.mysql.cj.jdbc.Driver");// 2. 建立數據庫連接connection = DriverManager.getConnection(URL, USER, PASSWORD);// 3. 創建 PreparedStatement 并設置參數String sql = "SELECT id,`name`,species,age FROM pets WHERE age > ?";preparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1,"3");// 4. 執行查詢resultSet = preparedStatement.executeQuery();// 5. 處理結果集while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("name");String species = resultSet.getString("species");int age = resultSet.getInt("age");System.out.println("ID: " + id + ", Name: " + name +",Species"+species+ ", Age: " + age);}} catch (ClassNotFoundException e) {System.err.println("數據庫驅動未找到: " + e.getMessage());} catch (SQLException e) {System.err.println("數據庫連接失敗: " + e.getMessage());} finally {// 6. 關閉資源try {if (resultSet != null) resultSet.close();if (preparedStatement != null) preparedStatement.close();if (connection != null) connection.close();} catch (SQLException e) {System.err.println("資源關閉失敗: " + e.getMessage());}}}
由于獲取數據庫連接資源比較繁瑣,因此要對數據庫連接進行管理。
對數據庫連接進行配置化管理連接串,用戶名,密碼以及驅動類,配置化管理就是把相關的字符串放入到一個文件中,這個文件可以是接口,可以是properties文件,可以是xml文件。
1.2 使用接口方法獲取連接
1.創建接口
public interface DBconfig {//把連接的地址,用戶名,密碼作為常量封裝到接口中public static final String URL = "jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC";public static final String USER = "root";public static final String PASSWORD = "226774";
}
2.創建連接工具類
public class ConnectionHelp {//靜態代碼塊,調用類時只加載一次static{try {Class.forName("com.mysql.cj.jdbc.Driver");} catch (ClassNotFoundException e) {throw new RuntimeException(e);}}//構造私有化,不能再創建ConnectionHelp對象private ConnectionHelp(){}//創建數據庫連接,封裝到方法中public static Connection getCon() throws SQLException {Connection connection = DriverManager.getConnection(DBconfig.URL,DBconfig.USER,DBconfig.PASSWORD);return connection;}
}
3.調用連接并測試查詢語句
public class TestConnection {public static void main(String[] args) throws SQLException {//調用連接方法ConnectionHelp.getCon();String sql = "select * from pets where id = ?";PreparedStatement preparedStatement = ConnectionHelp.getCon().prepareStatement(sql);preparedStatement.setInt(1,1);ResultSet resultSet = preparedStatement.executeQuery();while (resultSet.next()){String name = resultSet.getString("name");String species = resultSet.getString("species");int age = resultSet.getInt("age");System.out.println("姓名:"+name + " \t種類:" + species + " \t年齡:" + age);}}
}
1.3 使用properties文件獲取連接
? properties文件是一個文本文件,用key=value這樣的方法進行保存數據,由于不需要編譯,所以在idea中,要放入到資源文件夾(scr/main/resources)中。
1.創建config.properties配置文件
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC
username=root
userpass=226774
2.創建鏈接工具類
private static String driverName;private static String url;private static String userName;private static String userPass;static{InputStream in = ConnectionHelp2.class.getResourceAsStream("/conf.properties");Properties prop = new Properties();try {prop.load(in);driverName = prop.getProperty("driverName");url = prop.getProperty("url");userName = prop.getProperty("username");userPass = prop.getProperty("userpass");Class.forName(driverName);} catch (Exception e) {throw new RuntimeException(e);}}private ConnectionHelp2(){}public static Connection getCon() throws SQLException {Connection connection = DriverManager.getConnection(url,userName,userPass);return connection;}
3.調用連接并測試
此處與方法2相同,不同的是連接工具類的差異,以及調用時使用的連接工具類不同ConnectionHelp2.getCon();
public static void main(String[] args) throws SQLException {ConnectionHelp2.getCon();String sql = "select * from pets where id = ?";PreparedStatement preparedStatement = ConnectionHelp2.getCon().prepareStatement(sql);preparedStatement.setInt(1,1);ResultSet resultSet = preparedStatement.executeQuery();while (resultSet.next()){String name = resultSet.getString("name");String species = resultSet.getString("species");int age = resultSet.getInt("age");System.out.println("姓名:"+name + " \t種類:" + species + " \t年齡:" + age);}}
4.擴展:使用第三方組件讀取properties文件
第三方組件:非java的jdk提供的標準類,由非官方提供的類功能包
建議看一個第三方包,國產組件:hutool,指南位置:https://plus.hutool.cn/pages/index/
使用第三方組件的標準流程
1.要根據官網/maven依賴查詢網址,把組件依賴添加到項目中
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.35</version></dependency>
2.使用hutool進行數據庫連接的方法
Props props = new Props("conf.properties");
System.out.println(props.getStr("driverName"));Props props = new Props("conf.properties");// 從屬性文件中獲取屬性String driver = props.getStr("driverName");String url = props.getProperty("url");String user = props.getProperty("username");String pass = props.getProperty("userpass");// 加載驅動Class.forName(driver);//創建與數據庫的連接Connection connection = DriverManager.getConnection(url,user,pass);
1.4 使用數據庫連接池
1.什么是連接池
連接池(Connection Pool)是一種用于管理數據庫連接的技術。它的核心思想是預先創建并維護一組數據庫連接,當應用程序需要與數據庫交互時,從連接池中獲取一個連接,使用完畢后將連接歸還給連接池,而不是每次都創建新的連接或關閉連接。
2.為什么使用連接池
在傳統的數據庫連接方式中,每次與數據庫交互時都需要創建新的連接,使用完畢后關閉連接。這種方式存在以下問題:
性能開銷大:創建和關閉數據庫連接是非常耗時的操作,頻繁地創建和關閉連接會嚴重影響系統性能。
資源浪費:數據庫連接是有限的資源,頻繁創建和關閉連接會導致資源浪費,甚至可能導致數據庫連接耗盡。
難以管理:在高并發場景下,頻繁創建和關閉連接會導致數據庫連接數激增,增加數據庫的負擔。
連接池通過復用數據庫連接,解決了上述問題:
減少創建和關閉連接的開銷:連接池中的連接是預先創建好的,應用程序直接從連接池中獲取連接,使用完畢后歸還,避免了頻繁創建和關閉連接的開銷。
提高資源利用率:連接池中的連接可以被多個請求復用,減少了資源浪費。
控制連接數:連接池可以限制最大連接數,避免數據庫連接數過多導致數據庫崩潰。
3.如何理解連接池
可以將連接池類比為“共享單車”:
1.連接池:就像一個共享單車停放點,里面停放著一定數量的單車(數據庫連接)。
2.應用程序:就像需要使用單車的人。
3.獲取連接:當應用程序需要與數據庫交互時,從連接池中“借”一輛單車(獲取一個連接)。
4.使用連接:應用程序使用這個連接與數據庫交互。
5.歸還連接:使用完畢后,應用程序將連接“歸還”給連接池,而不是銷毀它。
通過這種方式,連接池實現了連接的復用,避免了頻繁創建和關閉連接的開銷。
4.使用druid連接池的步驟
步驟一:下載依賴
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency>
步驟二:編寫配置文件,注意根據本地的配置進行修改
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/pet_management
username=root
password=226774
InitialSize=5
MaxActive=20
MaxWait=3000
步驟三:把配置文件導入到連接池類中
public static DataSource dataSource;static {Props props = new Props("druid.properties");try {dataSource = DruidDataSourceFactory.createDataSource(props);} catch (Exception e) {throw new RuntimeException(e);}}public static Connection getCon() throws SQLException {return dataSource.getConnection();}