day4-mysql-JDBC

day4:JDBC

  1. JDBC 规范定义接口

    JDBC是访问数据库的标准和规范,访问数据库只需要调用JDBC中的接口与方法,数据驱动由数据库厂商提供

  2. 好处:

    1. 开发访问数据库的程序,只需要调用JDBC借口的方法即可,不关注类是如何实现的.
    2. 使用同一套 Java 代码,进行少量的修改就可以访问其他 JDBC 支持的数据库
  3. 核心API

    接口或者类作用
    DriverManager 类1) 管理和注册数据库驱动
    2) 得到数据库连接对象
    Connection 接口一个连接对象,可以用于创建 Statement 和 PreparedStatement
    Statement 接口一个 SQL 语句对象,用于将 SQL 语句发送给数据库服务器
    PreparedStatement 接口一个 SQL 语句对象,是 Statement 的子接口
    ResultSet 接口用于封装数据库查询的结果集,返回给客户端 Java 程序
  4. DriverManager的作用

    1) 管理和注册驱动
    2) 创建数据库的连接

    4.1方法

    静态方法描述
    Connection getConnection (String url, String user, String password)) 通过连接字符串,用户名,密码得
    到数据库的连接对象
    Connection getConnection (String url, Properties info)通过连接字符串,属性对象来得到
    连接对象

    4.2使用JDBC连接数据的四个参数

    user password URL 驱动类的字符串

    4.3连接URL地址的格式

    ​ 协议名:子协议://服务器名或者 IP:端口号/数据库名?参数=参数值

    ​ MySQL 中可以简写,前提是 MySQL 服务器必须是本地服务器,端口号是 3306
    简写格式:jdbc:mysql///数据库名
    如果数据库出现乱码,可以指定连接参数 characterEncoding=utf8 表示让数据库以 utf8 编码来处理
    数据。例如:jdbc:mysql://localhost:3306/数据库?characterEncoding=utf8

    4.4得到数据库对象

    1)使用用户名、密码、URL 得到连接对象
    String url="jdbc:mysql://192.168.220.128/db1";
    String user="root";
    String passord="root";
    Connection connection = DriverManager.getConnection(url,user,passord);
    //System.out.println(connection);2)使
    
    用属性文件和 URL 得到连接对象
    String url="jdbc:mysql://192.168.220.128/db1";
    String user="root";
    String passord="root";
    
    //使用属性文件
    Properties properties = new Properties();
    properties.put("user",user);
    properties.put("password",password);
    connection = DriverManager.getConnection(url,properties);
    System.out.println(connection)
    
  5. Connection 接口

    Connection 接口,具体的实现类由数据库厂商实现,代表一个连接对象。

    接口方法描述
    Statement createStatement()创建一条 SQL 语句对象
  6. Statement 接口

    代表一条语句对象,用于发送 SQL 语句给服务器,用于执行静态 SQL 语句并返回它所生成结果对象。

    Statement 接口中的方法描述
    int executeUpdate(String sql)用于发送 DML 语句 ,增删改的操作,insert
    update delete
    参数 :SQL 语句
    返回值:返回对数据库影响的行数
    ResultSet executeQuery(String sql)用于发送 DQL 语句,执行查询的操作。Select 参数:SQL 语句
    返回值:查询的结果集
  7. ResultSet接口

    作用:封装数据库查询的结果集,对结果集进行遍历,取出每一条记录

    ResultSet 接口方法描述
    boolean next()1) 游标向下移动 1 行
    2) 返回 boolean 型,如果还有下一条记录返回 true,否则返回 false
    数据类型 getXxx()) 1) 通过字段名,参数是 String 类型。返回不同的类型
    2) 通过列号,参数是整数,从 1 开始。返回不同类型
  8. 案例演示

    DDL 操作:使用 JDBC 在 MySQL 的数据库中创建一张学生表
    
    package com.ityouxin.jdbc;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class JdbcDemoForDDL {
     public static void main(String[] args) {
     String url="jdbc:mysql://192.168.220.128/db1";
     String user="root";
     String password="root";
     Connection connection=null;
     Statement statement=null;
     try {
     //1.加载注册驱动(可以省略) 思考为什么可以注册驱动?
     Class.forName("com.mysql.jdbc.Driver");
     //2.获取连接
     //jdbc:mysql://主机名:端口/数据库[?参数名=参数值]
     connection = DriverManager.getConnection(url,user,password);
     System.out.println(connection);
     //3. 定义 SQL 语句
     String sql = "CREATE TABLE student9 (\n" +
     " id INT PRIMARY KEY AUTO_INCREMENT,\n" +
     " NAME VARCHAR (20) NOT NULL,\n" +
     " gender BOOLEAN,\n" +
     " birthday DATE\n" +
     ")";
     //4.使用 Statement 对象执行 SQL 语句
     statement = connection.createStatement();
     //5.返回结果集 DDL 语句返回值 0
     int i= statement.executeUpdate(sql);
     System.out.println("执行返回:"+i);
     } catch (ClassNotFoundException | SQLException e) {
     e.printStackTrace();
     } finally {
     //6.释放资源
     if(statement!=null){
     	try {
     		statement.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     if(connection!=null){
     try {
     connection.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     }
     }
    }
    
     DML 操作:向学生表中添加 4 条记录,主键是自动增长
     
     
     package com.ityouxin.jdbc;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class JdbcDemoForDML {
     public static void main(String[] args) {
     String url="jdbc:mysql://192.168.220.128/db1";
     String user="root";
     String password="root";
     Connection connection=null;
     Statement statement=null;
     try {
     //1.加载注册驱动(可以省略) 思考为什么可以注册驱动?
     Class.forName("com.mysql.jdbc.Driver");
     //2.获取连接
     //jdbc:mysql://主机名:端口/数据库[?参数名=参数值]
     connection = DriverManager.getConnection(url,user,password);
     System.out.println(connection);
     //3. 定义 SQL 语句
     String sql = "INSERT INTO student9 VALUES\n" +
     "(NULL, '孙悟空', 1, '1993-03-24'),\n" +
     "(NULL, '白骨精', 0, '1995-03-24'),\n" +
     "(NULL, '猪八戒', 1, '1903-03-24'),\n" +
     "(NULL, '嫦娥', 0, '1993-03-11')";
     //4.使用 Statement 对象执行 SQL 语句
     statement = connection.createStatement();
     //5.返回结果集 DML 语句返回影响的行数
     int i= statement.executeUpdate(sql);
     System.out.println("执行返回:"+i);
     } catch (ClassNotFoundException | SQLException e) {
     e.printStackTrace();
     } finally {
     //6.释放资源
     if(statement!=null){
     try {
     statement.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     if(connection!=null){
     try {
     connection.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     }
     }
    }
    
    DQL 操作:查询学生表记录,并打印出学生信息
    
    package com.ityouxin.jdbc;
    import java.sql.*;
    public class JdbcDemoForDQL {
     public static void main(String[] args) {
     String url="jdbc:mysql://192.168.220.128/db1";
     String user="root";
     String password="root";
     Connection connection=null;
     Statement statement=null;
     ResultSet resultSet=null;
     try {
     //1.加载注册驱动(可以省略) 思考为什么可以注册驱动?
     Class.forName("com.mysql.jdbc.Driver");
     //2.获取连接
     //jdbc:mysql://主机名:端口/数据库[?参数名=参数值]
     connection = DriverManager.getConnection(url,user,password);
     System.out.println(connection);
     //3. 定义 SQL 语句
     String sql = "select * from student9";
     //4.使用 Statement 对象执行 SQL 语句
     statement = connection.createStatement();
     //5.返回结果集 DQL 语句返回结果集 ResultSet
     resultSet = statement.executeQuery(sql);
     if(resultSet!=null){
     while (resultSet.next()){
     int id = resultSet.getInt("id");
     String name = resultSet.getString("name");
     boolean gender = resultSet.getBoolean("gender");
     Date birthday = resultSet.getDate("birthday");
     System.out.println("编号:"+id+",姓名:"+name+",性别:"+(gender?"男":"
    女")+",生日:"+birthday);
     }
     }
     } catch (ClassNotFoundException | SQLException e) {
     e.printStackTrace();
     } finally {
     //6.释放资源
     if(resultSet!=null){
     try {
     resultSet.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     if(statement!=null){
     try {
     statement.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     if(connection!=null){
     try {
     connection.close();
     } catch (SQLException e) {
     e.printStackTrace();
     }
     }
     }
     }
    }
    
    
    
    

总结:

总结 JDBC 访问数据库的步骤

​ 1) 注册和加载驱动(可以省略)
​ 2) 获取连接
​ 3) Connection 获取 Statement 对象
​ 4) 使用 Statement 对象执行 SQL 语句
​ 5) 返回结果集
​ 6) 释放资源
释放资源 注意事项:

  1. 需要释放的对象:ResultSet 结果集,Statement 语句,Connection 连接
  2. 释放原则:先开的后关,后开的先关。ResultSet Statement Connection
  3. 在 finally 语句块中释放;

9.数据库工具类JdbcUtil

如果一个功能经常用到,我们建议把这个功能做成一个工具类,可以在不同的地方重用。

上一节示例中出现了很多重复的代码,我们可以把这些公共代码抽出来,创建一个 JdbcUtil 工具类.

可抽出的公共代码分析:
1) 用户名,密码,URL,驱动类配置
2) 数据库连接 getConnection
3) 关闭所有打开的资源
JdbcUtil 代码
package com.ityouxin.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Objects;
import java.util.Properties;
public class JdbcUtil {
 private static String url;
 private static String user;
 private static String password;
 static {
 try {
 Properties properties = new Properties();
 ClassLoader classLoader = JdbcUtil.class.getClassLoader();
 URL resource = classLoader.getResource("jdbc.properties");
 String path = Objects.requireNonNull(resource).getPath();
 System.out.println(path);
 properties.load(new FileReader(path));
 url=properties.getProperty("url");
 user=properties.getProperty("user");
 password= properties.getProperty("password");
 String driver = properties.getProperty("driver");
 Class.forName(driver);
 } catch (IOException | ClassNotFoundException e) {
 e.printStackTrace();
 }
 }
 /**
 * 获取连接
 */
 public static Connection getConnection() throws SQLException {
 return DriverManager.getConnection(url,user,password);
 }
 /**
 * 释放连接
 */
 public static void close(ResultSet resultSet, Statement statement, Connection connection){
 //6.释放资源
 if(resultSet!=null){
 try {
 resultSet.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }
 JdbcUtil.close(statement,connection);
 }
 public static void close( Statement statement, Connection connection){
 //6.释放资源
 if(statement!=null){
 try {
 statement.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }
 if(connection!=null){
 try {
 connection.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }
 }
}
  1. 案例:用户登录验证
1. 使用客户端工具创建用户表,初始用户记录
CREATE TABLE USER (
 id INT PRIMARY KEY AUTO_INCREMENT,
 NAME VARCHAR (20),
 PASSWORD VARCHAR (20)
);
INSERT INTO USER VALUES (NULL,'jack','123'),(NULL,'rose','456');

2. 编写程序得到从控制特输入的用户名和密码来查询数据库,验证输入的用户名和密码是否正确

package com.ityouxin.jdbc;
import com.ityouxin.util.JdbcUtil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDemoLogin {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.println("请输入用户名");
 String name= scanner.nextLine();
 System.out.println("请输入密码");
 String password=scanner.nextLine();
 login(name,password);
 }
 //验证登录
 public static void login(String name,String password){
 Connection connetion=null;
 Statement statement=null;
 ResultSet resultSet=null;
 try {
 connection= JdbcUtil.getConnection();
 statement=connection.createStatement();
 //通过拼接 SQL 查询记录
 String sql="select * from user where name='"+name+"' and
password='"+password+"'";
 resultSet = statement.executeQuery(sql);
 //如果有记录 则验证通过
 if(resultSet.next()){
 System.out.println("验证通过,欢迎您:"+name);
 }else {
 System.out.println("验证失败,请输入正确的用户名密码!");
 }
 } catch (SQLException e) {
 e.printStackTrace();
 }finally {
 JdbcUtil.close(resultSet,statement,connection);
 }
 }
}
 }
 

​ 升级和改正代码问题:SQL注入问题,不能让用户输入的内容和SQL语句进行简单的字符串拼接,此类问题可使用PrepareStatement接口来解决

  1. PrepareStatement接口

    1. PreparedStatement 是 Statement 接口的子接口,继承于父类接口中所有方法。它是一个预编译的 SQL 语句。
      作用:
      1) 有预编译的功能,提高 SQL 的执行效率
      2) 可以有效的防止 SQL 注入的问题,安全性更高。

    2. PrepareStatement 的使用

    创建 PrepareStatement 对象
    Connection 接口中的方法 描述
    PreparedStatement prepareStatement(String sql) 指定预编译的 SQL 语句,SQL 语句中使用占位
    符? 创建一个语句对象
    PrepareStatement 接口中的方法
    PrepareStatement 接口中的方法 描述
    int executeUpdate() 执行 DML,增删改的操作,返回影响的行数。
    ResultSet executeQuery() 执行 DQL,查询的操作,返回结果集

​ 3. 使用步骤:

​ 1)编写 SQL 语句,未知内容使用? 占位 :“SELECT * FROM user WHERE name=? AND password=?”;
​ 2)获得 PreparedStatement 对象
​ 3)设置实际参数:setXXX(占位符的位置,真实的值)
​ 4)执行参数化 SQ

登录改进代码

package com.ityouxin.jdbc;
import com.ityouxin.util.JdbcUtil;
import java.sql.*;
import java.util.Scanner;
public class JdbcDemoLogin02 {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.println("请输入用户名");
 String name= scanner.nextLine();
 System.out.println("请输入密码");
 String password=scanner.nextLine();
 login(name,password);
 }
 /**
 * 登录验证
 */
 public static void login(String name,String password){
 Connection connection=null;
 PreparedStatement statement=null;
 ResultSet resultSet=null;
 try {
 connection= JdbcUtil.getConnection();
 String sql="select * from user where name=? and password=?";
 statement=connection.prepareStatement(sql);
 statement.setString(1,name);
 statement.setString(2,password);
 System.out.println(sql);
 resultSet = statement.executeQuery();
 //如果有记录 则验证通过
 if(resultSet.next()){
 System.out.println("验证通过,欢迎您:"+name);
 }else {
 System.out.println("验证失败,请输入正确的用户名密码!");
 }
 } catch (SQLException e) {
 e.printStackTrace();
 }finally {
 JdbcUtil.close(resultSet,statement,connection);
 }
 }
}

案例:使用PreparedStatement查询一条数据,封装成一个学生类对象

package com.ityouxin.jdbc;
import com.ityouxin.entity.Student;
import com.ityouxin.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcDemoStudent {
 public static void main(String[] args) throws SQLException {
 	Connection connection = JdbcUtil.getConnection();
	String sql="select * from student where id=?";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
 	preparedStatement.setInt(1,5);
 	ResultSet resultSet = preparedStatement.executeQuery();
 if (resultSet.next()){
 	Student student = new Student();
 	student.setId(resultSet.getInt("id"));
 	student.setName(resultSet.getString("name"));
 	student.setGender(resultSet.getBoolean("gender"));
 	student.setBirthday(resultSet.getDate("birthday"));
 	System.out.println(student);
 }
 JdbcUtil.close(resultSet,preparedStatement,connection);
 }
}

案例:将多条语句封装成集合List,集合中的每个元素都是一个JavaBean实体类

package com.ityouxin.jdbc;
import com.ityouxin.entity.Student;
import com.ityouxin.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JdbcDemoStudents {
 public static void main(String[] args) throws SQLException {
 Connection connection = JdbcUtil.getConnection();
 String sql="select * from student ";
 PreparedStatement preparedStatement = connection.prepareStatement(sql);
 ResultSet resultSet = preparedStatement.executeQuery();
 List<Student> students = new ArrayList<>();
 while (resultSet.next()){
 Student student = new Student();
 student.setId(resultSet.getInt("id"));
 student.setName(resultSet.getString("name"));
 student.setGender(resultSet.getBoolean("gender"));
 student.setBirthday(resultSet.getDate("birthday"));
 System.out.println(student);
 students.add(student);
 }
 System.out.println(students);
 JdbcUtil.close(resultSet,preparedStatement,connection);
 }
}
  1. JDBC事务处理

    1. 事务有关的方法
      Connection 接口中与事务有关的方法 说明
      void setAutoCommit(boolean autoCommit) 参数是 true 或 false
      如果设置为 false,表示关闭自动提交,相当于开
      启事务
      void commit() 提交事务
      void rollback() 回滚事务

    2. 案例

      开发示例
      1)获取连接
      2)开启事务
      3)获取到 PreparedStatement
      4)使用 PreparedStatement 执行两次更新操作
      5)正常情况下提交事务
      6)出现异常回滚事务
      7)最后关闭资源
      
      package com.ityouxin.jdbc;
      import com.ityouxin.util.JdbcUtil;
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.SQLException;
      public class JdbcDemoTransaction {
       public static void main(String[] args) {
       Connection connection = null;
       PreparedStatement preparedStatement = null;
       try {
       connection = JdbcUtil.getConnection();
       //开启事务
       connection.setAutoCommit(false);
       //获取 preparedStatement
       //张三扣钱
       preparedStatement = connection.prepareStatement("update account set
      balance=balance-? where NAME=?");
       preparedStatement.setInt(1, 500);
       preparedStatement.setString(2, "张三");
       preparedStatement.executeUpdate();
       //模拟出现异常
       //System.out.println(3/0);
       //李四加钱
       preparedStatement = connection.prepareStatement("update account set
      balance=balance+? where name=?");
       preparedStatement.setInt(1, 500);
       preparedStatement.setString(2, "李四");
       preparedStatement.executeUpdate();
       //提交事务
       connection.commit();
       System.out.println("转账成功");
       } catch (Exception e) {
       e.printStackTrace();
       System.out.println("转账失败");
       try {
       // 异常,事务回滚
       connection.rollback();
       } catch (SQLException ex) {
       ex.printStackTrace();
       }
       } finally {
       JdbcUtil.close(preparedStatement, connection);
       }
       }
      }
                                                       
      

      JDBC连接池

      1. 其实就是一个容器(集合),存放数据库连接的容器。当系统初始化好后,容器被创建,容器中会申请
        一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给
        容器。
        优点:
        1) 节约资源
        2) 用户访问高效

      2. 相关接口方法
        DataSource 接口,在 javax.sql 包下, 用于连接物理数据源的工厂,作为 DriverManager 工具的替
        代方案,DataSource 对象是获取连接的首选方法。DataSource 接口由驱动程序供应商实现。
        1)获取连接:
        DataSource 接口中的方法说明
        getConnection() 获取数据源链接对象 Connection
        getConnection(String username, Strin password) 获取数据源链接对象 Connection 通过参数 用户名 密码

        2)归还连接:
        Connection.close()。如果连接对象 Connection 是从连接池中获取的,那么调用 Connection.close()方法,则不会再关闭连接了。而是归还连接

        数据库连接池技术常见实现

        名称描述
        C3P0开源数据库连接池技术 https://www.mchange.com/projects/c3p0/
        Druid数据库连接池实现技术,由阿里巴巴提供 项目地址
        https://github.com/alibaba/druid
      3. C3P0 使用

        代码演示

        public class DemoC3P0 {
         public static void main(String[] args) throws SQLException {
         //获取数据源
         ComboPooledDataSource dataSource = new ComboPooledDataSource();
         //按指定配置名称获取数据源
         //ComboPooledDataSource dataSource = new ComboPooledDataSource("otherc3p0");
         for (int i = 1; i <=12; i++) {
         Connection connection = dataSource.getConnection();
         System.out.println(i+" "+connection+",DB:"+connection.getCatalog());
         //归还连接
         if(i%5==0){
         connection.close();
         }
         }
         }
        }
        
      4. Druid 使用

        代码示例

        package com.ityouxin.datasource.druid;
        import com.alibaba.druid.pool.DruidDataSourceFactory;
        import javax.sql.DataSource;
        import java.sql.Connection;
        import java.util.Properties;
        public class DemoDruid {
         public static void main(String[] args) throws Exception {
         //1. 获取数据源
         Properties prperties=new Properties();
         prperties.load(DemoDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
         DataSource dataSource = DruidDataSourceFactory.createDataSource(prperties);
         Connection connection = dataSource.getConnection();
         System.out.println(connection+",Catalog:"+connection.getCatalog());
         }
        }
        
        
      5. 定义工具类

      1) 定义一个类 DataSouceUtil
      2) 提供静态代码块加载配置文件,初始化连接池对象
      3) 提供方法
      1. 获取连接方法:通过数据库连接池获取连接
      2. 释放资源
      3 获取连接池的方法
      package com.ityouxin.datasource.util;
      import com.alibaba.druid.pool.DruidDataSourceFactory;
      import javax.sql.DataSource;
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.util.Properties;
      public class DataSourceUtil {
       private static DataSource dataSource;
       static {
       Properties properties = new Properties();
       try {
      
      properties.load(DataSourceUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
       dataSource = DruidDataSourceFactory.createDataSource(properties);
       } catch (Exception e) {
       e.printStackTrace();
       }
       }
       /**
       * 获取连接
       */
       public static Connection getConnection() throws SQLException {
       return dataSource.getConnection();
       }
       /**
       * 释放资源
       */
       public static void close(Statement statement,Connection connection){
       close(null,statement,connection);
       }
       public static void close(ResultSet resultSet,Statement statement,Connection connection){
       if(resultSet!=null){
       try {
       resultSet.close();
       } catch (SQLException e) {
       e.printStackTrace();
       }
       }
       if(statement!=null){
       try {
       statement.close();
       } catch (SQLException e) {
       e.printStackTrace();
       }
       }
       if(connection!=null){
       try {
       connection.close();
       } catch (SQLException e) {
       e.printStackTrace();
       }
       }
       }
       /**
       * 获取数据库连接池
       * @return
       */
       public static DataSource getDataSource() {
       return dataSource;
       }
      }
      
  2. JdbcTemplate

    为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层, 以此建立一个 JDBC 存取框架.
    作为 SpringJDBC 框架的核心, JDBC 模板的设计目的是为不同类型的 JDBC 操作提供模板方法. 每个模板
    方法都能控制整个过程,并允许覆盖过程中的特定任务.通过这种方式,可以在尽可能保留灵活性的情况下,将
    数据库存取的工作量降到最低。

    1. JdbcTemplate 主要方法
    方法名描述
    update()执行 DML 语句。增、删、改语句
    queryForMap()将查询结果集封装为 map 集合,将列名作为 key,将值作为 value 将这条记
    录封装为一个 map 集合
    * 注意:这个方法查询的结果集长度只能是 1
    queryForList()查询结果将结果集封装为 list 集合
    * 注意:将每一条记录封装为一个 Map 集合,再将 Map 集合装载到 List 集合
    query()查询结果,将结果封装为 JavaBean 对象
    query 的参数:RowMapper
    * 一般我们使用 BeanPropertyRowMapper 实现类。可以完成数据到
    JavaBean 的自动封装
    new BeanPropertyRowMapper<类型>(类型.class)
    queryForObject()查询结果,将结果封装为对象
    * 一般用于聚合函数的查询
    execute()可以用于执行任何 SQL 语句,一般用于执行 DDL 语句
    1. 使用实例

      package com.ityouxin.jdbctemplate;
      import com.ityouxin.datasource.util.DataSourceUtil;
      import org.springframework.jdbc.core.JdbcTemplate;
      public class JdbcTemplateDemo1 {
       public static void main(String[] args) {
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtil.getDataSource());
       String sql="update emp set salary=? where id=?";
       jdbcTemplate.update(sql,8000,1);
       }
      }
      
    2. CURD 练习示例

      需求:
      1. 修改 1 号数据的 salary 为 10000
      2. 添加一条记录
      3. 删除刚才添加的记录
      4. 查询 id 为 1 的记录,将其封装为 Map 集合
      5. 查询所有记录,将其封装为 List
      6. 查询所有记录,将其封装为 Emp 对象的 List 集合
      7. 查询总记录数
      测试代码
      package com.ityouxin.jdbctemplate;
      import com.ityouxin.datasource.util.DataSourceUtil;
      import com.ityouxin.entity.Emp;
      import org.junit.Before;
      import org.junit.Test;
      import org.springframework.jdbc.core.BeanPropertyRowMapper;
      import org.springframework.jdbc.core.JdbcTemplate;
      import org.springframework.jdbc.core.RowMapper;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.util.List;
      import java.util.Map;
      public class JdbcTemplateDemo2 {
       //Junit 单元测试框架,可以让方法独立执行
       JdbcTemplate jdbcTemplate;
       @Before
       public void before(){
       jdbcTemplate = new JdbcTemplate(DataSourceUtil.getDataSource());
       }
       /**
       * 修改 1 号数据的 salary 为 10000
       */
       @Test
       public void test01(){
       String sql="update emp set salary=? where id=?";
       jdbcTemplate.update(sql,10000,1);
       }
       /**
       * 添加一条记录
       */
       @Test
       public void test02(){
       String sql="insert into emp values (null,?,?,?,?,?)";
       int count = jdbcTemplate.update(sql, "郭靖", "女", 10000, "2019-08-15", 1);
       System.out.println(count);
       }
       /**
       * 删除刚才添加的记录
       */
       @Test
       public void test03(){
       String sql="delete from emp where name=?";
       int count = jdbcTemplate.update(sql,"郭靖");
       System.out.println(count);
       }
       /**
       * 查询 id 为 1 的记录,将其封装为 Map 集合
       */
       @Test
       public void test04(){
       String sql="select * from emp where id=?";
       Map<String, Object> map = jdbcTemplate.queryForMap(sql, 1);
       System.out.println(map);
       }
       /**
       * 查询所有记录,将其封装为 List
       */
       @Test
       public void test05(){
       String sql="select * from emp ";
       List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
       System.out.println(maps);
       }
       /**
       * 查询所有记录,将其封装为 Emp 对象的 List 集合
       */
       @Test
       public void test06(){
       String sql="select * from emp ";
       List<Emp> emps = jdbcTemplate.query(sql, new RowMapper<Emp>() {
       @Override
       public Emp mapRow(ResultSet resultSet, int i) throws SQLException {
       Emp emp = new Emp();
       emp.setId(resultSet.getInt("id"));
       emp.setName(resultSet.getString("name"));
       emp.setGender(resultSet.getString("gender"));
       emp.setSalary(resultSet.getDouble("salary"));
       emp.setJoin_data(resultSet.getDate("join_date"));
       emp.setDept_id(resultSet.getInt("dept_id"));
       return emp;
       }
       });
       System.out.println(emps);
       }
       /**
       * 查询所有记录,将其封装为 Emp 对象的 List 集合
       */
       @Test
       public void test07(){
       String sql="select * from emp ";
       List<Emp> emps = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
       System.out.println(emps);
       }
       /**
       * 查询总记录数
       */
       @Test
       public void test08(){
       String sql="select count(*) from emp";
       Integer total = jdbcTemplate.queryForObject(sql, Integer.class);
       System.out.println(total);
       }
      }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值