一文帶你快速學(xué)會JDBC及獲取連接的五種方式
快速學(xué)會JDBC及獲取連接的五種方式
1. JDBC基本介紹
- JDBC為訪問不同的數(shù)據(jù)庫提供了統(tǒng)一的接口,為使用者屏蔽了細(xì)節(jié)問題
- Java程序員使用JDBC,可以連接任何提供了JDBC驅(qū)動程序的數(shù)據(jù)庫系統(tǒng),完成對數(shù)據(jù)庫的各種操作。
- JDBC基本原理圖

2. JDBC快速入門
2.1 JDBC程序編寫步驟
- 注冊驅(qū)動-加載Driver類
- 獲取連接-得到Connection
- 執(zhí)行增刪改查-發(fā)送SQL給MySQL執(zhí)行
- 釋放資源-關(guān)閉相關(guān)連接
2.2 案例演示
2.2.1 前置工作,在數(shù)據(jù)庫中建立對應(yīng)表
CREATE TABLE `actor`( id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(32) NOT NULL DEFAULT '', sex CHAR(1) NOT NULL DEFAULT '女', borndate DATETIME, phone VARCHAR(12));
2.2.2 前置工作,導(dǎo)入MySQL數(shù)據(jù)庫的對應(yīng)jar包
在項目下新建一個文件夾如libs,將對應(yīng)jar包拷入,并將其加入library中


public static void main(String[] args) throws SQLException {
//注冊驅(qū)動
Driver driver = new Driver();
String url="jdbc:mysql://localhost:3306/zxy_db01";
String user="root";
String psd = "123";
DriverManager.registerDriver(driver);
//獲得連接
Connection connection = DriverManager.getConnection(url,user,psd);
//執(zhí)行SQL語句
String sql = "insert into actor values(null, '劉德華', '男', '1970-11-11', '110')";
//statement 用于執(zhí)行靜態(tài) SQL 語句并返回其生成的結(jié)果的對象
Statement statement = (Statement) connection.createStatement();
int rows = statement.executeUpdate(sql);
System.out.println(rows > 0 ? "成功" : "失敗");
//關(guān)閉資源
statement.close();
connection.close();
}
然后我們再去查詢數(shù)據(jù)庫,就會發(fā)現(xiàn)已經(jīng)成功啦

3. 相關(guān)類的介紹
3.1 Statement
相信對于上面的代碼中你最好奇的就是Statement這個類,我們就來聊一聊這個。
基本介紹:
- 用于執(zhí)行靜態(tài)Sql語句并返回其生成結(jié)果
- 在連接建立后,需要對數(shù)據(jù)庫進行訪問,執(zhí)行命名或是SQL語句,可以通過Statement(存在SQL注入問題)PrepardStatement(預(yù)處理) CallableStatement(存儲過程)
- Statement對象執(zhí)行SQL語句,存在SQL注入風(fēng)險
- SQL注入是利用某些系統(tǒng)沒有對用戶輸入對數(shù)據(jù)進行充分對檢查,而在用戶輸入數(shù)據(jù)中注入非法對SQL語句段或命令,惡意攻擊數(shù)據(jù)庫
- 要防范SQL注入,只要用PreparedStatement(從Statement擴展而來),取代Statement就可以了
其實歸根究底,這個類就是一個用來調(diào)用執(zhí)行SQL語句的類。
3.2 ResultSet[結(jié)果集]
這個是執(zhí)行查詢的SQL時返回的對象,如下面這段代碼
String sql = "select id, name , sex, borndate from actor";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) { // 讓光標(biāo)向后移動,如果沒有更多行,則返回 false
int id = resultSet.getInt(1); //獲取該行的第 1 列
String name = resultSet.getString(2);//獲取該行的第 2 列
String sex = resultSet.getString(3);
Date date = resultSet.getDate(4);
System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
}
表示數(shù)據(jù)庫結(jié)果集的數(shù)據(jù)表,通常通過執(zhí)行查詢數(shù)據(jù)庫的語句生成。
ResultSet對象保持一個光標(biāo)指向其當(dāng)前的數(shù)據(jù)行。 最初,光標(biāo)位于第一行之前。 next方法將光標(biāo)移動到下一行,并且由于在ResultSet對象中沒有更多行時返回false ,因此可在while循環(huán)中使用循環(huán)來遍歷結(jié)果集。
3.3 PreparedStatement
這個類其實和上面介紹的Statement效果類似,相當(dāng)于Statement的改進版,增加了預(yù)處理過程避免了sql注入現(xiàn)象(簡單來講就是破獲你的數(shù)據(jù)庫中的信息),下面我們就來聊聊它
- PreparedStatement執(zhí)行的SQL語句中的參數(shù)用問號(?)來表示,調(diào)用PreparedStatement對象額setXxx()方法來設(shè)置這些參數(shù),setXxx()方法有兩個參數(shù),第一個參數(shù)是要設(shè)置的SQL語句中的參數(shù)的索引(從1開始),第二個是設(shè)置的SQL語句中的參數(shù)的值。
- 調(diào)用executeQuery(),返回ResultSet對象
- 調(diào)用 executeUpdate(),執(zhí)行增刪改等操作。
其優(yōu)點也是極其明顯的
- 不再使用+拼接SQL語句,減少語法錯誤
- 有效的解決了SQL注入問題
- 大大減少了編譯次數(shù),效率提高
話不多說,我們直接上案例
String sql = "select name , pwd from admin where name =? and pwd = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "劉德華");
preparedStatement.setString(2, "123");
ResultSet resultSet = preparedStatement.executeQuery(sql);
if (resultSet.next()) { //如果查詢到一條記錄,則說明該管理存在
System.out.println("恭喜, 登錄成功"); }
else {
System.out.println("對不起,登錄失敗");
}
4. 關(guān)閉資源
在JDBC編碼過程中,我們創(chuàng)建了resultSet,statement,connection等資源,這些資源在使用完畢后一定要進行關(guān)閉資源,關(guān)閉的過程中遵循從里到外的原則,因為在增刪改查中的操作中都要用到這樣的關(guān)閉操作
resultSet.close(); statement.close(); connection.close();
5. 獲取數(shù)據(jù)庫連接的五種方式
方式一
直接通過Driver類獲得連接
public void way1() throws SQLException {
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/zxy_db01";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("psd","123");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
方式二
通過反射的方式加載Driver類獲得連接
public void way2() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clzz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clzz.newInstance();
String url = "jdbc:mysql://localhost:3306/zxy_db01";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("psd","123");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
方式三
使用DriverManager替換Driver獲得連接
public void way3() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clzz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clzz.newInstance();
String url="jdbc:mysql://localhost:3306/zxy_db01";
String user="root";
String psw = "123";
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
方式四
使用Class.forName自動完成驅(qū)動注冊獲得鏈接
public void way4() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/zxy_db01";
String user="root";
String psd = "123";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
方式五
借助配置文件獲得來獲得連接

user=root psd=123 url=jdbc:mysql://localhost:3306/zxy_db01 driver=com.mysql.jdbc.Driver
public void way5() throws SQLException, ClassNotFoundException, IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("psd");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, psd);
System.out.println(connection);
}
相信看完本篇你對jdbc已經(jīng)有了不錯的了解了
總結(jié)
到此這篇關(guān)于一文快速學(xué)會JDBC及獲取連接的五種方式的文章就介紹到這了,更多相關(guān)學(xué)會JDBC及獲取連接方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot2.0 @ConfigurationProperties使用詳解
這篇文章主要介紹了Spring Boot2.0 @ConfigurationProperties使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
更簡單更高效的Mybatis?Plus最新代碼生成器AutoGenerator
這篇文章主要為大家介紹了更簡單更高效的Mybatis?Plus最新代碼生成器AutoGenerator使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
詳解@Autowired(required=false)注入注意的問題
這篇文章主要介紹了@Autowired(required=false)注入注意的問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04

