day43_jdbc

今日内容

0 复习昨日
1 SQL注入问题
2 PreparedStatement
3 完成CRUD练习
4 ORM
5 DBUtil (properties)

6 事务操作

0 复习昨日

已经找人提问…

1 SQL注入

1.1 什么是SQL注入

用户输入的数据中有SQL关键词,导致在执行SQL语句时出现一些不正常的情况.这就是SQL注入!


出现SQL注入是很危险

在这里插入图片描述

1.2 避免SQL注入

问题出现在用户输入数据时,里面有关键词,再配合字符串拼接导致出现SQL注入.所以为了避免SQL注入,可以在用户输入数据到SQL之前,先把SQL语句预编译,预处理后,JDBC就会知道此SQL需要几个参数,后续再将用户输入的数据给参数填充.

这就是PreparedStatement

2 PreparedStatement【重点】

PreparedStatement是Statement的子接口,用来预处理SQL语句

PreparedStatement使用

  • 先写SQL语句,SQL语句中的参数不能直接拼接,而是使用?占位
  • 使用ps预处理SQL语句,处理的?号,ps内部就会知道此SQL语句需要几个参数
  • 再动态给?处填充值
package com.qf.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc 登录-使用预处理语句完成
 */
public class Demo2_LoginPlus {

    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:" );
        String username = scanner.nextLine( );

        System.out.println("请输入密码:" );
        String password = scanner.nextLine( );

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

        // 改造SQL,将拼接变量,变成?占位
        String sql = "select * from tb_user where username = ? and password = ?";
        System.out.println("处理前:  " + sql);

        // 由之前的Statement换成PreparedStatement
        // 将改造好的SQL,传入方法
        PreparedStatement ps = conn.prepareStatement(sql);
        System.out.println("处理后: " + ps );

        // 给处理好的占位参数赋值
        // ps.setXxx() 给指定Xxx类型赋值
        // 第一个?,下标是1
        ps.setString(1,username);
        ps.setString(2,password);

        System.out.println("填充后: " + ps );

        //【特别注意!!!!】 此处executeQuery不需要再传入SQL参数!!!
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            System.out.println("登录成功!!" );
        } else {
            System.out.println("用户名或密码错误!" );
        }

        rs.close();
        ps.close();
        conn.close();
    }
}
请输入用户名:
111
请输入密码:
111' or '1=1
处理前:  select * from tb_user where username = ? and password = ?
处理后: select * from tb_user where username = ** NOT SPECIFIED ** and password = ** NOT SPECIFIED **
填充后: select * from tb_user where username = '111' and password = '111\' or \'1=1'
用户名或密码错误!

3 完成CRUD练习

3.1 插入

package com.qf.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc  使用预处理语句插入数据
 */
public class Demo3_insert {

    public static void main(String[] args) throws Exception {

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

        // 1 先改造SQL(由拼接变成?)
        String sql = "insert into tb_user (id,username,password,phone,createTime,money,sex) values (?,?,?,?,?,?,?)";

        // 2 预处理
        PreparedStatement ps = conn.prepareStatement(sql);

        // 3 给?处赋值
        ps.setInt(1,5);
        ps.setString(2,"亚鹏");
        ps.setString(3,"333000");
        ps.setString(4,"333333");
        // 【特别注意!!!】 setDate的参数,设置是java.sql.Date
        // 我们常用的是java.util.Date
        // java.sql.Date是java.util.Date的子类
        // java.sql.Date有个构造方法,可以通过毫秒值创建日期
        // 通过常用的java.util.Date获得毫秒值
        ps.setDate(5,new java.sql.Date(new java.util.Date().getTime()));

        // 如果需要设置日期时间 yyyy-MM-dd HH:mm:ss
        // 使用ps.setTimestamp();

        ps.setDouble(6,3000.1);
        ps.setInt(7,1);
        // 【特别注意!!!】 此处不要再填参数
        int num = ps.executeUpdate( );

        if (num > 0) {
            System.out.println("插入成功" );
        }
        ps.close();
        conn.close();
    }
}

3.2 更新

package com.qf.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
public class Demo4_update {

    public static void main(String[] args) throws  Exception{

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

        // 1 改造sql
        String sql = "update tb_user set username = ? , createTime = ? , money = ? where id = ?";
        // 2 预处理
        PreparedStatement ps = conn.prepareStatement(sql);
        // 3 填充?
        ps.setString(1,"小谢");

        Date utilDate = new Date( );
        utilDate.setYear(100);
        utilDate.setMonth(0);
        utilDate.setDate(1);
        long time = utilDate.getTime( );
        ps.setDate(2,new java.sql.Date(time));

        ps.setDouble(3,4000.1);
        ps.setInt(4,5);

        int num = ps.executeUpdate( );

        if (num > 0) {
            System.out.println("更新成功" );
        }

        ps.close();
        conn.close();
    }
}

3.3 删除

    public static void main(String[] args) throws  Exception{

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

        // 1 改造sql
        String sql = "delete from tb_user where id = ?";
        // 2 预处理
        PreparedStatement ps = conn.prepareStatement(sql);
        // 3 填充?
        ps.setInt(1,5);

        int num = ps.executeUpdate( );

        if (num > 0) {
            System.out.println("删除成功" );
        }

        ps.close();
        conn.close();
    }

4 事务处理

事务是逻辑一组操作,要么全部成功,要么全部失败!


使用mysql客户端操作事务

  • 因为mysql支持事务,且每句话都在事务内,且自动提交
  • 所以关闭自动提交事务,手动开启事务 start transaction
  • 正常写sql/执行sql
  • 一切正常,提交事务 commit
  • 如果不正常,要回滚 rollback

JDBC也可以完成事务操作

  • conn.setAutoCommit(false) 关闭自动提交,就相当于是开启手动管理
  • 正常的处理sql
  • 一切正常,提交事务 conn.commit()
  • 如果不正常,回滚 conn.rollback()

演示: 以转账案例演示

package com.qf.tx;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc 以转账为案例演示
 * --------------------
 * Statement语句和PreparedStatement语句
 * 与事务操作没有影响
 */
public class Demo6_TX {

    // 张三转账给李四
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

            // 【1 开启事务】
            conn.setAutoCommit(false);

            // 张三的钱减少100
            String sql1 = "update account set money = money - 100 where id = 1";
            ps1 = conn.prepareStatement(sql1);
            int num = ps1.executeUpdate( );
            if (num > 0) {
                System.out.println("张三转账(-100)完成!");
            }

            System.out.println(1/0 ); // 模拟在转账中,出现异常,后续不执行

            // 李四的钱要增加100
            String sql2 = "update account set money = money + 100 where id = 2";
            ps2 = conn.prepareStatement(sql2);
            int num2 = ps2.executeUpdate( );
            if (num2 > 0) {
                System.out.println("李四转账(+100)完成!");
            }

            // 【2 一切顺利,提交事务】
            conn.commit();

        } catch (Exception e) {
            try{
                // 【3 不顺利,中间有异常,回滚事务】
                conn.rollback();
            }catch (Exception e2) {
                System.out.println("回滚事务异常!!" );
                e2.printStackTrace();
            }
            System.out.println("SQL异常!!!");
            e.printStackTrace( );
        } finally {
            try {
                ps1.close( );
                ps2.close( );
                conn.close( );
            } catch (Exception e) {
                System.out.println("关流时有异常!!");
                e.printStackTrace( );
            }
        }
    }
}

另外发现: 建立与Mysql连接后,关流之前,可以执行很多次SQL语句

5 ORM【重点】

5.1 什么是ORM

目前使用JDBC完成了CRUD,但是现在是进行CRUD,增删改方法要设计很多参数,查询的方法需要设计集合才能返回.


在实际开发中,我们需要将零散的数据封装到对象处理.

ORM (Object Relational Mapping) 对象关系映射

是指数据库表Java的实体类有关系,可以进行映射

  • 数据库表 --> Java的类
    • tb_user —> User.java
  • 字段 --> 类的属性
    • id int --> private int id;
    • username varchar --> private String username;
  • 一行数据 --> 类的对象

5.2 实体类

实体类: 数据表中零散数据的载体,用来封装数据.

  • 表名 设计 类名
  • 将列名设计成属性名
    • id --> id
    • create_time --> createTime (下划线转驼峰)
  • 将列的数据类型设计成属性的数据类型
  • 给类提供对应set get

一般项目中一个表就会对应一个实体类,所有的实体类都会放在model/entity/pojo/javabeen包结构中


将来写项目,数据库设计完,搭建完项目,第一件事件就是根据表结构,创建实体类

package com.qf.model; // 包
public class User {   // 实体类,是表名
	// 属性是字段名
    private int id;
    private String username;
    private String password;
    private String phone;
    private Date createTime;
    private double money;
    private int sex;
    
    // setter getter...
}

在这里插入图片描述

5.3 使用ORM完成CRUD

5.3.1 查询使用ORM封装数据

package com.qf.orm;

import com.qf.model.User;

import java.sql.*;
import java.util.Scanner;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc 登录完成,查询到数据,将数据封装到User对象
 * ---------------------------------------------
 * 使用ORM封装数据,将查询得到结果集封装到User对象中
 * 即登录成功  User对象中有值
 *  登录不成功 User对象不存在
 */
public class Demo7_Login_ORM {


    public static void main(String[] args) throws Exception{

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:" );
        String username = scanner.nextLine( );

        System.out.println("请输入密码:" );
        String password = scanner.nextLine( );

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

        String sql = "select * from tb_user where username = ? and password = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);

        ResultSet rs = ps.executeQuery( );

        // 声明用于封装数据表数据的实体类
        User user = null;

        if (rs.next()) {
            // 从结果集取值
            int id = rs.getInt("id");
            String uname = rs.getString("username");
            String pwd = rs.getString("password");
            String phone = rs.getString("phone");
            Date createTime = rs.getDate("createTime");
            double money = rs.getDouble("money");
            int sex = rs.getInt("sex");

            // 创建封装数据用的实体类对象
            user = new User();
            // 开始封装
            user.setId(id);
            user.setUsername(uname);
            user.setPassword(pwd);
            user.setPhone(phone);
            user.setCreateTime(createTime); // java.sql.Date是java.util.Date的子类
            user.setMoney(money);
            user.setSex(sex);
        }

        if (user != null) {
            System.out.println("登录成功!" );
            System.out.println("个人信息为:" + user );
        } else {
            System.out.println("登录失败!" );
        }
    }
}

5.3.2 插入使用ORM封装数据

package com.qf.orm;

import com.qf.model.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
public class Demo8_Insert_ORM {

    public static void main(String[] args) {
        User user = new User( );
        user.setId(6);
        user.setUsername("李冰");
        user.setPassword("123456" );
        user.setCreateTime(new Date());
        user.setMoney(4000.1);
        user.setSex(2);
        user.setPhone("222333");

        insert(user);
    }

    public static void insert(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2217?useSSL=false", "root", "123456");

            String sql = "insert into tb_user (id,username,password,phone,createTime,money,sex) values (?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,user.getId());
            ps.setString(2,user.getUsername());
            ps.setString(3,user.getPassword());
            ps.setString(4,user.getPhone());
            ps.setDate(5,new java.sql.Date(user.getCreateTime().getTime()));
            ps.setDouble(6,user.getMoney());
            ps.setInt(7,user.getSex());

            int num = ps.executeUpdate( );
            if (num > 0) {
                System.out.println("注册成功!" );
            }
        } catch (Exception e) {
            System.out.println("SQL异常!!!" );
            e.printStackTrace();
        } finally {
            try{
                ps.close();
                conn.close();
            }catch (Exception e) {
                System.out.println("关流异常!!" );
                e.printStackTrace();
            }
       }
    }
}

6 DBUtil【理解,会用】

DBUtil操作数据库的工具类,因为发现每次操作数据库,JDBC的步骤第1,2,5步完全重复的,即加载驱动,获得连接对象,已经最后的关流是每次都要写但每次都是一样的!!!


现在设计工具类,简化第1,2,5步

  • 设计个方法,调用直接获得连接对象
  • 设计个方法,调用直接关闭全部的流对象
package com.qf.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
public class DBUtil {

    // 创建Properties类对象,专用于操作properties文件
    private static final Properties properties = new Properties();

    /**
     * 加载驱动的目的是为了在JVM中有sql运行的环境
     * 该环境有一份就行了,不用重复加载
     * ------------------------------------
     * static 静态代码块
     * 1) 保证内存中只有一份
     * 2) 保证随着类加载而加载,即该代码块会执行
     */
    static {

        // 通过反射的技术获得字节码文件
        // 再通过字节码文件将配置文件读取成输入流
        InputStream inputStream = DBUtil.class.getResourceAsStream("/jdbc.properties");
        try {
            // 再通过流获得其中数据
            properties.load(inputStream);
            // 从properties对象取值
            Class.forName(properties.getProperty("driverClass"));
        } catch (Exception e) {
            System.out.println("加载驱动异常!!" );
            e.printStackTrace( );
        }
    }

    /**
     * 一般会将关于JDBC配置信息,抽取出来,形成一个配置文件,方便维护
     * 文件类型是properties文件,该文件类似map,键值对类型
     * 名字 jdbc.properties
     * 位置 src/jdbc.properties
     * 内容
     */
    public static Connection getConnection() {
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username") ,properties.getProperty("password") );
        } catch (Exception e) {
            System.out.println("获得连接出异常!!!" );
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 关闭所有流
     */
    public static void closeAll(Connection conn, Statement s) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace( );
            }
        }

        if (s != null) {
            try {
                s.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace( );
            }
        }
    }

    public static void closeAll(Connection conn, Statement s, ResultSet rs){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace( );
            }
        }

        if (s != null) {
            try {
                s.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace( );
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace( );
            }
        }
    }
}

在src下创建jdbc.properties文件

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java2217?useSSL=false
username=root
password=123456

tion throwables) {
throwables.printStackTrace( );
}
}

    if (s != null) {
        try {
            s.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace( );
        }
    }

    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace( );
        }
    }
}

}


在src下创建jdbc.properties文件

```properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java2217?useSSL=false
username=root
password=123456
  • 33
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

师范大学通信大怨总

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值