java連接數(shù)據(jù)庫(kù)的5種方式解讀
方式一:直接導(dǎo)入第三方庫(kù)驅(qū)動(dòng)類

這種加載方式在jdbc入門(mén)時(shí)已經(jīng)用過(guò),這個(gè)driver屬于第三方庫(kù),。為靜態(tài)加載,靈活性差,依賴性搶
方式二:使用反射機(jī)制獲取

方式一和方式二代碼
package com.hsp.edu;
import com.mysql.cj.jdbc.Driver;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
//java獲取連接的5種方式
public class JdbcConnect {
public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
connect01();
connect02();
}
//方式一,直接導(dǎo)入第三方庫(kù)驅(qū)動(dòng)類
public static void connect01() throws SQLException {
//獲取驅(qū)動(dòng)
Driver driver = new Driver();
//獲取連接
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false&useSer" +
"verPrepStmts=true&characterEncoding=utf-8&useSSL=false";
//將用戶名和密碼放入到Properities對(duì)象中
Properties properties = new Properties();
properties.setProperty("user","root");//用戶
properties.setProperty("password","888888");//密碼
final Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
//方式二:使用反射加載Driver:動(dòng)態(tài)加載,更加的靈活,減少依賴
public static void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, InvocationTargetException {
//獲取Driver類的字節(jié)碼文件對(duì)象
final Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//注意:在用字節(jié)碼文件對(duì)象獲取Driver對(duì)象時(shí),直接newInstance被idea提示已經(jīng)棄用
final Constructor<?> Constructor = clazz.getDeclaredConstructor();
final Driver driver = (Driver)Constructor.newInstance();
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false&useSer" +
"verPrepStmts=true&characterEncoding=utf-8&useSSL=false";
//將用戶名和密碼放入到Properities對(duì)象中
Properties properties = new Properties();
properties.setProperty("user","root");//用戶
properties.setProperty("password","888888");//密碼
final Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
}
方式三:使用DriverManager類

//方式三:使用DriverManager替換Driver
public static void connect03() throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, ClassNotFoundException {
//DriverManager類支持更好的獲取連接的方法,可以直接將用戶和密碼作為參數(shù),而不用存儲(chǔ)到Properities
final Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
final Constructor<?> constructor = clazz.getDeclaredConstructor();
final Driver driver =(Driver)constructor.newInstance();
//創(chuàng)建url和user和password
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false&useSer" +
"verPrepStmts=true&characterEncoding=utf-8&useSSL=false";
String user = "root";
final String password = "888888";
DriverManager.registerDriver(driver);//注冊(cè)Driver驅(qū)動(dòng)
final Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}方式四:在加載Driver類時(shí)自動(dòng)完成驅(qū)動(dòng)注冊(cè)(以此簡(jiǎn)化代碼)

Driver類的底層源碼
靜態(tài)代碼塊:在類加載的時(shí)候會(huì)執(zhí)行一次
從上面的Driver類的源碼可以看出,在加載Driver類的時(shí)候,其靜態(tài)代碼塊,已經(jīng)完成了驅(qū)動(dòng)的注冊(cè)
//方式四:加載Driver時(shí)自動(dòng)完成注冊(cè)(這種方式使用的最多,推薦使用)
public static void connect04() throws ClassNotFoundException, SQLException {
//使用反射加載了Driver類
//在加載 Driver類時(shí),完成注冊(cè)
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false&useSer" +
"verPrepStmts=true&characterEncoding=utf-8&useSSL=false";
String user = "root";
String password="888888";
final Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}方式五:將信息寫(xiě)入到配置文件
一個(gè)疑問(wèn):為什么不寫(xiě)`Class.forName("com.mysql.cj.jdbc.Driver");也可以獲取到連接?

在驅(qū)動(dòng)文件中META-INF下面的services有個(gè)com.mysql.cj.jdbc.Driver文件里面已經(jīng)記錄了加載的全類名。
我們的程序?qū)?huì)直接按照文件中的內(nèi)容進(jìn)行加載

使用配置文件,當(dāng)我們需要修改的時(shí)候就不用修改代碼,只用修改配置文件即可
解惑:Properties類和properties文件沒(méi)有直接關(guān)系(以前認(rèn)為如果創(chuàng)建了一個(gè)properies文件,就已經(jīng)存在了一個(gè)Properties對(duì)象)
Properties類只是和properties文件存儲(chǔ)的格式一樣(以鍵值對(duì)的形式存儲(chǔ)),但是在使用的時(shí)候還是需要將文件中的數(shù)據(jù)讀取到程序中 配置文件目錄

//方式五:進(jìn)一步優(yōu)化,將信息寫(xiě)入到配置文件
public static void connect05() throws IOException, ClassNotFoundException, SQLException {
//通過(guò)Properties對(duì)象獲取配置文件信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));//此時(shí)已經(jīng)將配置文件的信息讀取到了Properties中
//獲取相關(guān)信息
final String user = properties.getProperty("user");//用戶
final String password = properties.getProperty("password");//密碼
final String url = properties.getProperty("url");//url
final String driver = properties.getProperty("driver");
Class.forName(driver);//注冊(cè)驅(qū)動(dòng)
final Connection connection = DriverManager.getConnection(url, user, password);//獲取連接
System.out.println(connection);
}課堂練習(xí)

屬性文件

package com.hsp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/*
參考老師代碼,使用方式5完成
1.創(chuàng)建news表
2.使用jdbc添加5條記錄
3.修改id=1的記錄content改成一個(gè)新的記錄
*/
public class Jdbc02 {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//前置工作:獲取配置文件中的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql1.properties"));//讀取信息到集合中
final String driver = properties.getProperty("driver");//獲取全類名
final String url = properties.getProperty("url");//獲取url
final String user = properties.getProperty("user");//獲取用戶名
final String password = properties.getProperty("password");//獲取密碼
System.out.println(properties);
//1.注冊(cè)驅(qū)動(dòng)
Class.forName(driver);
//2.獲取連接
final Connection connection = DriverManager.getConnection(url, user, password);
//3.執(zhí)行 SQL語(yǔ)句
//String sql1 = "CREATE TABLE news(id INT,content VARCHAR(32))";
String sql2="INSERT INTO news VALUES (1,'居民健康'),(2,'商品健康'),(3,'大熊貓')";
String sql3="UPDATE news SET content='湖北'WHERE id=1;";
final Statement statement = connection.createStatement();
//final int row1 = statement.executeUpdate(sql1);//返回影響的行數(shù)
final int row2 = statement.executeUpdate(sql2);//返回影響的行數(shù)
final int row3 = statement.executeUpdate(sql3);
//:驗(yàn)證是否執(zhí)行成功
/*if(row1!=0){
System.out.println("執(zhí)行成功");
}else {
System.out.println("執(zhí)行失敗");
}*/
if (row2!=0){
System.out.println("執(zhí)行成功");
}else {
System.out.println("執(zhí)行失敗");
}
if(row3!=0){
System.out.println("執(zhí)行成功");
}else {
System.out.println("執(zhí)行失敗");
}
//4.關(guān)閉資源
statement.close();
connection.close();
}
}
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot項(xiàng)目自定義靜態(tài)資源映射規(guī)則的實(shí)現(xiàn)代碼
在開(kāi)發(fā)Web應(yīng)用時(shí),我們經(jīng)常需要處理文件上傳與訪問(wèn),?傳統(tǒng)做法可能是使用Nginx反向代理,但對(duì)于小型項(xiàng)目或快速開(kāi)發(fā)場(chǎng)景,我們可以直接用?Spring MVC的靜態(tài)資源映射? 功能,本文將基于WebMvcConfigurer手寫(xiě)配置,實(shí)現(xiàn) ?本地文件目錄映射為Web URL,需要的朋友可以參考下2025-08-08
淺析SpringBoot中使用thymeleaf找不到.HTML文件的原因
這篇文章主要介紹了SpringBoot中使用thymeleaf找不到.HTML文件的原因分析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
springboot使用redis實(shí)現(xiàn)從配置到實(shí)戰(zhàn)
本文主要介紹了springboot使用redis ,采用的是RedisTemplate的形式,還有一種采用spring支持的注解進(jìn)行訪問(wèn)緩存,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
java實(shí)現(xiàn)動(dòng)態(tài)上傳多個(gè)文件并解決文件重名問(wèn)題
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)動(dòng)態(tài)上傳多個(gè)文件,并解決文件重名問(wèn)題的方法,感興趣的小伙伴們可以參考一下2016-03-03
兩天沒(méi)解決的問(wèn)題chatgpt用了5秒搞定隱藏bug
這篇文章主要為大家描述了我用了兩天沒(méi)解決的問(wèn)題chatgpt用了5秒搞定的全程介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
java實(shí)現(xiàn)簡(jiǎn)單猜數(shù)字游戲
這篇文章主要介紹了java實(shí)現(xiàn)簡(jiǎn)單猜數(shù)字游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12
java實(shí)現(xiàn)讀取txt文件并以在每行以空格取數(shù)據(jù)
今天小編就為大家分享一篇java實(shí)現(xiàn)讀取txt文件并以在每行以空格取數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07

