­

JDBC-第1篇-基礎

  • 2019 年 10 月 22 日
  • 筆記

話不多說,直接開擼程式碼。

1.首先自己的環境使用的是maven項目+idea工具+mysql8.0.18 (使用maven項目的好處就是方便,不用手動導入相關的驅動包,在pom.xml配置即可)

2.第一步:在pom中導入mysql的驅動包(這裡注意跟mysql的版本,導入驅動包的版本也不一樣,我是用的是8.0.18版本,需要導入5.1.48版本

1 <!--jdbc驅動包-->  2 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->  3 <dependency>  4    <groupId>mysql</groupId>  5    <artifactId>mysql-connector-java</artifactId>  6    <version>5.1.48</version>  7 </dependency>

3.第二步:建立一個TestDriver.java來寫測試用例(結論寫在程式碼裡面)

  3.1 通過Diriver實現類對象獲取連接

 1   /**   2      * 注意:我這裡是maven項目。通過Diriver實現類對象獲取連接。   3      * 1.首先引入jdbc的驅動jar包,我本地用的是mysql8版本。導入mysql-connector-java,版本為5.1.48+   4      * 2.然後創建一個Diriver實現類的對象   5      * 3.準備連接數據基本資訊   6      * 4.調用Driver介面的connect方法,連接資料庫   7      *   8      * @throws SQLException   9      */  10     @Test  11     public void testDriver1() throws SQLException {  12         //1.創建一個Diriver實現類的對象  13         Driver driver = new Driver();  14  15         //2.準備連接數據基本資訊  16         String url = "jdbc:mysql://localhost:3306/test";  17         Properties properties = new Properties();  18         properties.put("user", "root");  19         properties.put("password", "root");  20  21         //3.調用Driver介面的connect連接資料庫  22         Connection connect = driver.connect(url, properties);  23         System.out.println(connect);  24     }

    3.2 在前面的基礎上,將資料庫基本資訊寫成jdbc.properties配置文件,進行讀取(配置文件需要放在根目錄下進行讀取

/**       *       * 1.首先引入jdbc的驅動jar包,我本地用的是mysql8版本。導入mysql-connector-java為5.1.48       * 2.創建一個jdbc.properties文件       * 3.定義一個方法讀取jdbc.properties文件,並在該方法創建連接       * 4.調用方法,返回Driver介面的connect連接資料庫       *       * @throws Exception       */      @Test      public void testDriver2() throws Exception {          Connection connection = getConnection();          System.out.println(connection);      }        /**       * 1.把配置連接放入到一個jdbc.properties文件中,然後統一讀取。解耦合       * 2.讀取properties文件中的連接資訊       * 3.創建連接       *       * @return       */      public Connection getConnection() throws Exception, ClassNotFoundException, IllegalAccessException, InstantiationException {          //1.首先定義本地變數          String driverClass = null;          String jdbcUrl1 = null;          String user = null;          String password = null;            //2.讀取類路徑下的jdbc.properties,此配置文件需要放置到resources文件夾下。          InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");          Properties properties = new Properties();          properties.load(resourceAsStream);            //3.分別獲取配置對象的值          driverClass = properties.getProperty("driver");          jdbcUrl1 = properties.getProperty("jdbcUrl");          user = properties.getProperty("user");          password = properties.getProperty("password");            //4.通過反射拿到Driver連接對象          Driver driver = (Driver) Class.forName(driverClass).newInstance();            Properties info = new Properties();          info.put("user", user);          info.put("password", password);            //獲取連接          Connection connect = driver.connect(jdbcUrl1, info);          return connect;      }

   3.3  通過DriverManager驅動的管理類來獲取Connection對象,從而實現連接資料庫

 1 /**   2      * DriverManager是驅動的而管理類   3      * 好處:   4      * 1.通過 DriverManager,可以重載getConnection()方法獲取資料庫連接,較為方便   5      * 2.可以同時管理多個驅動程式:若註冊了多個資料庫連接,則調用getConnection()方法時,傳入的參數不同,即返回的連接不同。   6      * <p>   7      * 可以通過單獨封裝成一個方法,從jdbc.properties中進行讀取   8      */   9     @Test  10     public void testDriverManager3() throws Exception {  11  12         //1.準備連接資料庫的4個連接資訊(mysql配置資訊)  13         String driverClass = "com.mysql.jdbc.Driver";  14         String jdbcUrl1 = "jdbc:mysql://localhost:3306";  15         String user = "root";  16         String password = "root";  17  18         //1.準備連接資料庫的4個連接資訊(假設是oracle的配置資訊,模擬用,其實還是mysql的。)  19         String driverClass2 = "com.mysql.jdbc.Driver";  20         String jdbcUrl2 = "jdbc:mysql://localhost:3306";  21         String user2 = "root";  22         String password2 = "root";  23  24         //載入資料庫驅動  25         //這裡使用Class.forName方法直接註冊驅動,因為對應的Driver中有註冊驅動的靜態程式碼快  26         //DriverManager.registerDriver((java.sql.Driver) Class.forName(driverClass).newInstance());  27         //註冊mysql的驅動  28         Class.forName(driverClass);  29         //註冊oracle的驅動  30         Class.forName(driverClass2);  31  32         //得到mysql的連接  33         Connection connection = DriverManager.getConnection(jdbcUrl1, user, password);  34  35         //得到oracle的連接  36         Connection connection2 = DriverManager.getConnection(jdbcUrl2, user2, password2);  37  38         System.out.println(connection);  39         System.out.println(connection2);  40     }

  3.4 在上面創建了連接後,下面就是,通過jdbc想指定數據表中插入一條記錄:

 1 /**   2      * 在上面創建了連接後,下面就是:   3      * 通過jdbc想指定數據表中插入一條記錄   4      * 1.Connection和Statement都是應用程式和資料庫伺服器的連接資源,使用後需要關閉   5      * 2.需要注意在出現異常的情況下,來進行try catch來進行關閉   6      * 3.executeUpdate中可以為insert,update,delete。但是不能為select   7      * 4.關閉的順序是,先獲取的後關閉,先關閉Statement,後關閉Connection   8      */   9     @Test  10     public void testStatement4() throws Exception {  11         //1.獲取資料庫連接  12         Connection connection = null;  13  14         Statement statement = null;  15  16         connection = getConnection();  17  18         try {  19             //2.準備插入的sql預計  20             //插入插座  21             //String sql = " insert into customers (name,email,brith) values (11,222,'2019-10-23')";  22             //刪除操作  23             //String sql = " delete from customers where id =3";  24             //更新操作  25             String sql = " update customers set name ='羅傑', email='117@qq/com' ,brith='1995-05-21' where id=6";  26  27             //3.執行插入,添加,刪除  28             //3.1獲取操作sql語句的Statement對象,調用Connection的createStatement()方法來獲取  29             statement = connection.createStatement();  30             //3.2調用Statement對象的executeUpdate(sql)執行sql語句進行插入  31             int i = statement.executeUpdate(sql);  32             System.out.println("執行結果返回值:"+i);  33         } catch (SQLException e) {  34             e.printStackTrace();  35         } finally {  36             //4.關閉Statement對象  37             if (statement != null) {  38                 try {  39                     statement.close();  40                 } catch (SQLException e) {  41                     e.printStackTrace();  42                 }  43             }  44             //5.關閉連接  45             if (connection != null) {  46                 try {  47                     connection.close();  48                 } catch (SQLException e) {  49                     e.printStackTrace();  50                 }  51             }  52         }  53     }

  3.5 在上一個基礎上,封裝了一個JdbcTools方法,通過工具類來進行獲取鏈接和關閉來鏈接

 1 /**   2      * 在上一個基礎上,封裝了一個JdbcTools方法,通過工具類來進行獲取鏈接和關閉來鏈接   3      * @throws Exception   4      */   5     @Test   6     public void testStatementUseTools5() throws Exception{   7         //1.通過工具類獲取jdbc連接   8         Connection connection = JdbcTools.getConnection();   9         //2.創建Statement對象  10         Statement statement = connection.createStatement();  11         try {  12             //2.準備插入的sql預計  13             //插入插座  14             //String sql = " insert into customers (name,email,brith) values (11,222,'2019-10-23')";  15             //刪除操作  16             //String sql = " delete from customers where id =3";  17             //更新操作  18             String sql = " update customers set name ='小黑', email='117@qq/com' ,brith='1995-05-21' where id=6";  19  20             //3.執行插入,添加,刪除  21             //3.1獲取操作sql語句的Statement對象,調用Connection的createStatement()方法來獲取  22             //3.2調用Statement對象的executeUpdate(sql)執行sql語句進行插入  23             int i = statement.executeUpdate(sql);  24             System.out.println(i);  25         } catch (SQLException e) {  26             e.printStackTrace();  27         } finally {  28            JdbcTools.release(connection,statement);  29         }  30  31     }

工具類程式碼如下:

  1 package testhutool.jdbc;    2    3 import com.mysql.jdbc.Driver;    4    5 import java.io.InputStream;    6 import java.sql.Connection;    7 import java.sql.ResultSet;    8 import java.sql.SQLException;    9 import java.sql.Statement;   10 import java.util.Properties;   11   12 /**   13  * jdbc的工具方法   14  */   15 public class JdbcTools {   16     /**   17      * 1.獲取連接的公共方法   18      * 通過讀取配置文件,獲取連接   19      *   20      * @return   21      * @throws Exception   22      * @throws ClassNotFoundException   23      * @throws IllegalAccessException   24      * @throws InstantiationException   25      */   26     public static Connection getConnection() throws Exception, ClassNotFoundException, IllegalAccessException, InstantiationException {   27         //首先定義本地變數   28         String driverClass = null;   29         String jdbcUrl1 = null;   30         String user = null;   31         String password = null;   32   33         //讀取類路徑下的jdbc.properties,此配置文件需要放置到resources文件夾下。   34         InputStream resourceAsStream = Class.forName("testhutool.jdbc.JdbcTools").getClassLoader().getResourceAsStream("jdbc.properties");   35         Properties properties = new Properties();   36         properties.load(resourceAsStream);   37   38         //分別獲取配置對象的值   39         driverClass = properties.getProperty("driver");   40         jdbcUrl1 = properties.getProperty("jdbcUrl");   41         user = properties.getProperty("user");   42         password = properties.getProperty("password");   43   44         //通過反射拿到Driver連接對象   45         Driver driver = (Driver) Class.forName(driverClass).newInstance();   46   47         Properties info = new Properties();   48         info.put("user", user);   49         info.put("password", password);   50   51         //獲取連接   52         Connection connect = driver.connect(jdbcUrl1, info);   53   54         return connect;   55   56     }   57   58   59     /**   60      * 關閉連接資源   61      * @param connection   62      * @param statement   63      */   64     public static void release(Connection connection, Statement statement) {   65         release(null,connection,statement);   66     }   67   68   69     /**   70      * 關閉連接資源   71      * @param resultSet 結果集   72      * @param connection 資料庫連接對象   73      * @param statement   74      */   75     public static void release(ResultSet resultSet,Connection connection, Statement statement) {   76   77         //3.關閉resultSet對象   78         if (resultSet != null) {   79             try {   80                 statement.close();   81             } catch (SQLException e) {   82                 e.printStackTrace();   83             }   84         }   85   86         //4.關閉Statement對象   87         if (statement != null) {   88             try {   89                 statement.close();   90             } catch (SQLException e) {   91                 e.printStackTrace();   92             }   93         }   94         //5.關閉連接   95         if (connection != null) {   96             try {   97                 connection.close();   98             } catch (SQLException e) {   99                 e.printStackTrace();  100             }  101         }  102  103  104     }  105 }

3.6 最後就是通過RecordSet獲取結果集,分別遍歷獲取結果:

 1 /**   2      * ResultSet來獲取結果集,封裝了使用jdnc進行查詢的結果   3      * 1.調用了Statement對象的executeQuery(sql),可以得到結果集   4      * 2.ResultSet返回的實際上是一張數據表,有一個指針指向數據表的第一行的前面   5      * 可以調用next()方法。來檢測下一行是否有效,如果該方法有效,且指針下移,相當於Iterator對象的hasNext和next的結合體   6      * 3.當指針到下一行的時候,可以通過gteXxx(index)或者getXxx(columnName)獲取每一列的值。   7      * 4.ResultSet當然也需要進行關閉   8      */   9     @Test  10     public void  testResultSet6() throws Exception{  11  12         //獲取id=6的customers的數據表數據,並列印  13         Connection connection = null;  14         Statement statement = null;  15         ResultSet resultSet = null;  16  17         //1.獲取連接Connection  18         connection = JdbcTools.getConnection();  19         //2.獲取Statement  20         statement = connection.createStatement();  21         //3.準備SQL  22         String sql = "select * from customers";  23         //4.執行查詢。得到ResultSet結果集  24         resultSet = statement.executeQuery(sql);  25         //5.處理ResultSet  26         while(resultSet.next()){  27  28             int id = resultSet.getInt(1);  29             String name = resultSet.getString("name");  30             String email = resultSet.getString("email");  31             Date brith = resultSet.getDate("brith");  32             String brith1 = resultSet.getString("brith");  33             System.out.println("id:"+id+",name:"+name+",email:"+email+",brith:"+brith+",brith1:"+brith1);  34  35         }  36  37         //6.關閉資料庫資源  38         JdbcTools.release(resultSet,connection,statement);  39     }

總結:通過上面的基礎的獲取Connection連接,獲取Statement對象,ResultSet對象。簡單封裝了工具類方法,完成的java到資料庫的增刪改查。