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到数据库的增删改查。