欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java連接數(shù)據(jù)庫的5種方式解讀

 更新時間:2024年04月02日 08:59:23   作者:thulium_  
這篇文章主要介紹了java連接數(shù)據(jù)庫的5種方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教<BR>

方式一:直接導(dǎo)入第三方庫驅(qū)動類

這種加載方式在jdbc入門時已經(jīng)用過,這個driver屬于第三方庫,。為靜態(tài)加載,靈活性差,依賴性搶

方式二:使用反射機制獲取

方式一和方式二代碼

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)入第三方庫驅(qū)動類
    public static void connect01() throws SQLException {
 
        //獲取驅(qū)動
        Driver driver = new Driver();
        //獲取連接
        String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false&useSer" +
                "verPrepStmts=true&characterEncoding=utf-8&useSSL=false";
        //將用戶名和密碼放入到Properities對象中
        Properties properties = new Properties();
        properties.setProperty("user","root");//用戶
        properties.setProperty("password","888888");//密碼
        final Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }
    //方式二:使用反射加載Driver:動態(tài)加載,更加的靈活,減少依賴
    public static void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, InvocationTargetException {
        //獲取Driver類的字節(jié)碼文件對象
        final Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        //注意:在用字節(jié)碼文件對象獲取Driver對象時,直接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對象中
        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ù),而不用存儲到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);//注冊Driver驅(qū)動
        final Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
 
    }

方式四:在加載Driver類時自動完成驅(qū)動注冊(以此簡化代碼)

Driver類的底層源碼 

靜態(tài)代碼塊:在類加載的時候會執(zhí)行一次 

從上面的Driver類的源碼可以看出,在加載Driver類的時候,其靜態(tài)代碼塊,已經(jīng)完成了驅(qū)動的注冊

//方式四:加載Driver時自動完成注冊(這種方式使用的最多,推薦使用)
    public static void connect04() throws ClassNotFoundException, SQLException {
        //使用反射加載了Driver類
        //在加載 Driver類時,完成注冊
        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);
 
    }

方式五:將信息寫入到配置文件

一個疑問:為什么不寫`Class.forName("com.mysql.cj.jdbc.Driver");也可以獲取到連接?

在驅(qū)動文件中META-INF下面的services有個com.mysql.cj.jdbc.Driver文件里面已經(jīng)記錄了加載的全類名。

我們的程序?qū)苯影凑瘴募械膬?nèi)容進行加載

使用配置文件,當我們需要修改的時候就不用修改代碼,只用修改配置文件即可

解惑:Properties類和properties文件沒有直接關(guān)系(以前認為如果創(chuàng)建了一個properies文件,就已經(jīng)存在了一個Properties對象)

Properties類只是和properties文件存儲的格式一樣(以鍵值對的形式存儲),但是在使用的時候還是需要將文件中的數(shù)據(jù)讀取到程序中 配置文件目錄

//方式五:進一步優(yōu)化,將信息寫入到配置文件
    public static void connect05() throws IOException, ClassNotFoundException, SQLException {
        //通過Properties對象獲取配置文件信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));//此時已經(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);//注冊驅(qū)動
        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改成一個新的記錄
 */
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.注冊驅(qū)動
      Class.forName(driver);
        //2.獲取連接
        final Connection connection = DriverManager.getConnection(url, user, password);
 
        //3.執(zhí)行 SQL語句
       //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);
 
        //:驗證是否執(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é)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。 

相關(guān)文章

  • javaWeb使用Kaptcha組件生成驗證碼

    javaWeb使用Kaptcha組件生成驗證碼

    這篇文章主要為大家詳細介紹了javaWeb使用Kaptcha組件生成驗證碼的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • java 抽象類與接口的區(qū)別介紹

    java 抽象類與接口的區(qū)別介紹

    這篇文章主要介紹了java 抽象類與接口的區(qū)別介紹的相關(guān)資料,需要的朋友可以參考下
    2016-10-10
  • java 多線程-鎖詳解及示例代碼

    java 多線程-鎖詳解及示例代碼

    本文主要介紹 Java 多線程鎖的基礎(chǔ)知識,這里整理了相關(guān)資料及示例代碼有興趣的小伙伴可以參考下
    2016-09-09
  • Mybatis中單雙引號引發(fā)的慘案及解決

    Mybatis中單雙引號引發(fā)的慘案及解決

    這篇文章主要介紹了Mybatis中單雙引號引發(fā)的慘案及解決方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 使用SpringBoot中整合Redis

    使用SpringBoot中整合Redis

    這篇文章主要介紹了使用SpringBoot中整合Redis,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • 使用java實現(xiàn)http多線程斷點下載文件(一)

    使用java實現(xiàn)http多線程斷點下載文件(一)

    Java 多線程斷點下載文件基本原理:利用URLConnection獲取要下載文件的長度、頭部等相關(guān)信息,并設(shè)置響應(yīng)的頭部信息,本文將詳細介紹,需要了解更多的朋友可以參考下
    2012-12-12
  • Springboot自定義mvc組件如何實現(xiàn)

    Springboot自定義mvc組件如何實現(xiàn)

    這篇文章主要介紹了Springboot自定義mvc組件如何實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11
  • Java模擬撲克牌洗牌實現(xiàn)生成52張撲克的方法示例

    Java模擬撲克牌洗牌實現(xiàn)生成52張撲克的方法示例

    這篇文章主要介紹了Java模擬撲克牌洗牌實現(xiàn)生成52張撲克的方法,涉及Java數(shù)組遍歷、重排及輸出等相關(guān)操作技巧,需要的朋友可以參考下
    2018-01-01
  • Mybatis-Plus中的查詢指定字段

    Mybatis-Plus中的查詢指定字段

    在使用Mybatis-Plus進行數(shù)據(jù)查詢時,可以通過指定字段來優(yōu)化查詢效率,方法一和方法二分別執(zhí)行不同的SQL語句,其中方法二在執(zhí)行時通常會更高效,因為它可能通過減少數(shù)據(jù)處理量和優(yōu)化查詢結(jié)構(gòu)來提升性能,比較兩種方法的SQL執(zhí)行情況
    2024-09-09
  • JAVA中使用雙括號來初始化靜態(tài)常量的小技巧

    JAVA中使用雙括號來初始化靜態(tài)常量的小技巧

    這篇文章主要介紹了JAVA中使用雙括號來初始化靜態(tài)常量的小技巧,需要的朋友可以參考下
    2014-06-06

最新評論