JDBC技术【封装JDBC工具类、Statement的使用、PreparedStatement的使用(重点)、ResultSet的使用】(二)-全面详解(学习总结---从入门到深化)

目录

封装JDBC工具类

Statement的使用

PreparedStatement的使用(重点)

ResultSet的使用

ORM编程思想


封装JDBC工具类

 properties文件

#连接Mysql数据库的URL
url=jdbc:mysql://localhost:3306/itjdbc
#连接数据库的用户名
username=root
#连接数据库的密码
pwd= XXXX
#数据库驱动名称
driver=com.mysql.jdbc.Driver

JdbcUtil工具类

/**
* Jdbc工具类
*/
public class JdbcUtils {
    private static String url;
    private static String name;
    private static String pwd;
    static {
        try{
            //实例化Properties对象
            Properties prop = new Properties();
            //获取读取properties文件的字节输入流 对象
            InputStream is = JdbcTest2.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //读取properties文件并解析
            prop.load(is);
            //获取连接数据库的url
            url = prop.getProperty("url");
            //获取连接数据库的用户名
            name = prop.getProperty("username");
            //获取连接数据库的密码
            pwd = prop.getProperty("pwd");
            //获取数据库驱动全名
            String drivername = prop.getProperty("driver");
            //加载并注册驱动
            Class.forName(drivername);  }catch(Exception e){
            e.printStackTrace();
       }
   }
    //获取数据库连接对象
    public static Connection getConnection()
      {
          Connection connection = null;
          try {
           connection = DriverManager.getConnection(url,name,pwd);
       } catch (SQLException throwables) {
            throwables.printStackTrace();
       }
        return connection;
   }
    //关闭连接对象
    public static void closeConnection(Connection connection){
        try {
            connection.close();
       } catch (SQLException throwables) {
            throwables.printStackTrace();
       }
   }
    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
       } catch (SQLException throwables) { throwables.printStackTrace();
       }
   }
    //事务回滚
    public static void rollback(Connection connection){
        try {
            connection.rollback();
       } catch (SQLException throwables) {
            throwables.printStackTrace();
       }
   }
    //关闭Statement对象
    public static void closeStatement(Statement statement){
        try {
            statement.close();
       } catch (SQLException throwables) {
            throwables.printStackTrace();
       }
   }
    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet) {
        try {
            resultSet.close();
       } catch (SQLException throwables) {
            throwables.printStackTrace();
       }
   }
    //DML操作时关闭资源
    public static void closeResource(Statement statement,Connection connection){
        //先关闭Statement对象
        closeStatement(statement);
        //在关闭Connection对象
        closeConnection(connection);
       }
    //查询时关闭资源
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
   }
}

Statement的使用

 Statement简介

Statement接口特点

用于执行静态 SQL 语句并返回它所生成结果的对象。 由 createStatement 创建,用于发送简单的 SQL 语句(不支持动态绑 定)。

注意: 由于Statement对象是一个执行静态SQL语句的对象,所以该对 象存在SQL注入风险。

 JDBC中三种Statement对象

Statement:用于执行静态 SQL 语句。

PreparedStatement:用于执行预编译SQL语句。

CallableStatement:用于执行数据库存储过程。

 通过Statement添加数据

创建表

CREATE TABLE `users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `userage` int(11) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

添加数据

/**
* Statement对象的使用
*/
public class StatementTest {
    /**
     * 添加用户
     */
    public void insertUsers(String username,int userage){
        Connection connection = null;
        Statement statement = null;
        try{
            //获取Connection对象。
            connection = JdbcUtils.getConnection();
            //获取Statement对象
            statement = connection.createStatement();
            //定义需要执行的SQL语句
            String sql = "insert into users values(default,'"+username+"',"+userage+")";
            //执行SQL,返回boolean值,如果sql有结果集返回,那么返回值为true,如果没有结果集返回,则返回false。
            boolean execute = statement.execute(sql);
            System.out.println(execute);
       }catch(Exception e){
            e.printStackTrace();
       }finally{
          JdbcUtils.closeResource(statement,connection);
       }
   }
}

通过Statement修改数据

    /**
     * 修改用户信息
     */
    public void updateUsers(int userid,String username,int userage){
        Connection connection = null;
        Statement statement  = null;
        try{
                //获取连接对象
               connection = JdbcUtils.getConnection();
               //获取Statement对象
               statement = connection.createStatement();
               //定义sql语句
               String sql ="update users set username='"+username+"',userage="+userage+"
where userid="+userid;
               //执行sql语句
               int i = statement.executeUpdate(sql);
               System.out.println(i);
           }catch(Exception e){
                e.printStackTrace();
           }finally{
              JdbcUtils.closeResource(statement,connection);
           }
   }

通过Statement删除数据

    /**
     * 根据用户ID删除用户
     */
    public void deleteUsersById(int userid){
        Connection connection =null;
        Statement statement = null;
        try{
            //获取数据库连接
            connection = JdbcUtils.getConnection();
            //获取Statement对象
            statement = connection.createStatement();
            //定义执行删除语句
            String sql = "delete from users where userid="+userid;
            //执行sql
            int i = statement.executeUpdate(sql);
            System.out.println(i);
       }catch(Exception e){
            e.printStackTrace();
       }finally{
           JdbcUtils.closeResource(statement,connection);
       }
   }

PreparedStatement的使用(重点)

 PreparedStatement对象简介

继承自 Statement 接口,由 preparedStatement方法创建。 PreparedStatement具有预编译SQL语句能力,所以 PreparedStatement 对象比 Statement 对象的效率更高,由于实 现了动态的参数绑定,所以可以防止 SQL 注入,所以我们一般都使 用 PreparedStatement。

PreparedStatement对象的特点:

PreparedStatement 接口继承 Statement 接口

PreparedStatement 效率高于 Statement

PreparedStatement 支持动态绑定参数

PreparedStatement 具备 SQL 语句预编译能力 使用

PreparedStatement 可防止出现 SQL 注入问题

 PreparedStatement 的预编译能力

语句的执行步骤 

1、语法和语义解析

2、优化 sql 语句,制定执行计划

3、执行并返回结果

 但是很多情况,我们的一条 sql 语句可能会反复执行,或者每次执 行的时候只有个别的值不同(比如 select 的 where 子句值不同, update 的 set 子句值不同,insert 的 values 值不同)。 如果每次都 需要经过上面的词法语义解析、语句优化、制定执行计划等,则效 率就明显不行 了。所谓预编译语句就是将这类语句中的值用占位符 替代,可以视为将 sql 语句模板化或者说参数化预编译语句的优势 在于:一次编译、多次运行,省去了解析优化等过程;此外预编译 语 句能防止 sql 注入

 通过PreparedStatement添加数据

/**
* PreparedStatement使用的测试类
*/
public class PreparedStatementTest {
    /**
     * 添加用户
     */
    public void insertUsers(String username,int userage){
        Connection connection = null;
        PreparedStatement ps = null;
        try{
            //获取数据库连接
            connection = JdbcUtils.getConnection();
            //定义Sql。?是PreparedStatement对象中的绑定参数的占位符。问号的位置是从1开始计数的
            String sql = "insert into users values(default,?,?)";
            //创建PreparedStatement对象
            ps = connection.prepareStatement(sql);
            //完成参数的绑定
            ps.setString(1,username);
            ps.setInt(2,userage);
            int i = ps.executeUpdate();
            System.out.println(i);
       }catch(Exception e){
            e.printStackTrace();
       }finally{
            JdbcUtils.closeResource(ps,connection);
       }
   }
}

通过PreparedStatement修改数据

/**
     * 根据用户ID修改用户姓名与年龄
     */
    public void updateUsersById(int userid,String username,int userage){
            Connection connection = null;
            PreparedStatement ps = null;
           try{
               //获取数据库连接对象
               connection = JdbcUtils.getConnection();
               //创建PreparedStatement对象
               ps = connection.prepareStatement("update users set username = ?,userage=? where userid = ?");
               //参数绑定
               ps.setString(1,username);
               ps.setInt(2,userage);
               ps.setInt(3,userid);
               int i = ps.executeUpdate();
               System.out.println(i);
           }catch(Exception e){
               e.printStackTrace();
           }finally{
               JdbcUtils.closeResource(ps,connection);
           }
   }

通过PreparedStatement删除数据

/**
     * 根据用户ID删除指定用户
     */
    public void deleteUsersById(int userid){
            Connection conn = null;
            PreparedStatement ps = null;
        try{
            //获取数据库连接对象
            conn = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = conn.prepareStatement("delete from users where userid = ? ");
            //绑定参数
            ps.setInt(1,userid);
            int i = ps.executeUpdate();
            System.out.println(i);
       }catch (Exception e){
            e.printStackTrace();
       }finally{
            JdbcUtils.closeResource(ps,conn);
       }
   }

ResultSet的使用

 ResultSet简介

ResultSet接口的特点

ResultSet用来存放数据库查询操作获得结果集,通过对ResultSet 的操作可以获取查询到的结果集数据。

注意: ResultSet 对象中存放的并不是我们查询到的所有的结果集。它 采用分块加载的方式来载入结果集数据

 ResultSet特点

1、ResultSet 对象具有指向其当前数据行的指针。最初,指针被置于第一行之前。next 方法将指针移 动到下一行;因为该方法在 ResultSet 对象中没有下一行时返回 false,所以可以在 while 循环中使 用它来迭代结果集。

2、默认的 ResultSet 对象仅有一个向前移动的指针。因此,只能迭代它一次,并且只能按从第一行到 最后一行的顺序进行。

3、ResultSet 接口提供用于获取当前行检索列值的获取方法(getBoolean、getLong 等)。可以使用 列的索引位置或列的名称检索值。

 ResultSet使用原理

 通过ResultSet获取查询结果

/**
* 获取结果集测试类
*/
public class ResultSetTest {
    /**
     * 查询所用用户
     */
    public void selectUsersAll(){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try{
            //获取数据库连接
            connection = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = connection.prepareStatement("select * from users");
            //执行查询
            resultSet = ps.executeQuery();
            //操作ResultSet对象获取查询的结果集
            while(resultSet.next()){
                //获取列中的数据
                int userid = resultSet.getInt("userid");
                String username = resultSet.getString("username");
                int userage = resultSet.getInt("USERAGE");
                System.out.println(userid+" "+username+" "+userage);
           }
       }catch(Exception e){
            e.printStackTrace();
       }finally{
          JdbcUtils.closeResource(resultSet,ps,connection);
       }
   }
}

ORM编程思想

 ORM简介

对象关系映射(英语:Object Relational Mapping,简称ORM,或 O/R mapping)是一种为了解决面向对象语言与关系数据库存在的 互不匹配的现象。

 实体类

实体类就是一个定义了属性,拥有getter、setter、无参构造方法 (基本必备)的一个类。实体类可以在数据传输过程中对数据进行 封装,相当于一个“工具”、“容器”、“载体”,能存储、传输数据,能 管理数据。

实体类特点:

1 实体类名,尽量和数据库中的表名一一对应

2 实体类中的属性对应数据库表中的字段,相关的命名最好也一一对应

3 实体类内方法主要有,getter、setter方法,用于设置、获取数据

4 实体类属性一般为private类型,方法为public类型

5 实体类应该有,无参、有参构造方法

 ORM使用

Users实体类

/**
* 实体类,存放Users表中的数据
*/
public class Users {
    private int userid;
    private String username;
    private int userage;
    public int getUserid() {
        return userid;
   }
    
public void setUserid(int userid) {
        this.userid = userid;
   }
    
public String getUsername() {
        return username;
   }
    
public void setUsername(String username)
  {
        this.username = username;
   }
    
public int getUserage() {
        return userage;
   }
    
public void setUserage(int userage) {
        this.userage = userage;
   }
}

ORM映射

/**
     * 查询所用用户
*/
    public List<Users> selectUsersAll(){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List<Users> list = new ArrayList<>();
        try{
            //获取数据库连接
            connection = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = connection.prepareStatement("select * from users");
            //执行查询
            resultSet = ps.executeQuery();
            //操作ResultSet对象获取查询的结果集
            while(resultSet.next()){
                //获取列中的数据
                int userid = resultSet.getInt("userid");
                String username = resultSet.getString("username");
                int userage = resultSet.getInt("USERAGE");
                //System.out.println(userid+" "+username+" "+userage);
                //ORM映射处理
                Users users = new Users();
                users.setUserid(userid); 
                users.setUsername(username);
                users.setUserage(userage);
                list.add(users);
           }
       }catch(Exception e){
            e.printStackTrace();
       }finally{
          JdbcUtils.closeResource(resultSet,ps,connection);
       }
        return list;
   }

猜你喜欢

转载自blog.csdn.net/m0_58719994/article/details/131648727