数据库(DataBase)-PrepareStatement代码举例

5.PrepareStatement对象

PrepareStatement可以实现Statement的功能,同时可以防止Sql注入,同时效率更好。

1.提取工具类:

一次编写,多次调用。

本文数据库:

CREATE DATABASE JdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;

USE JdbcStudy;

CREATE TABLE `users`(
	`id` INT PRIMARY KEY,
	`NAME` VARCHAR(40),
	`PASSWORD` VARCHAR(40),
	`email` VARCHAR(60),
	`birthday` DATE
);

INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES
(1,'ALita','123456','Alita@qq.com','2022-12-04'),
(2,'Edwin','456798','Edwin@qq.com','2000-12-04'),
(3,'Jarvis','789123','Jarvis@qq.com','2000-12-04');

select * from user;

配置文件:

driver = com.mysql.jdbc.Driver

url = jdbc:mysql://localhost:3306/jdbcStudy?useUnicode = true&characterEncoding = utf8&useSSL = true

username = root

password = 1234

工具类:

package com.Edwin.lession02.utils;

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

/**
 * @author Edwin D
 * @date 2020.5.21 上午 9:22
 */
public class JdbcUtils {

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try{
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);

            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

//            驱动只需加载一次即可。
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//        获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

//    释放资源
    public static void release(Connection con, Statement sta, ResultSet res){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (sta != null) {
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

1.新增-Insert

package com.Edwin.lession03;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 1:54
 */
public class TestInsert2 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pres = null;

        try {
            con = JdbcUtils.getConnection();

//            PreparedStatement开始于Statement的有区别:
//            使用“?”占位符来代替参数,可以提高效率,
            String sql = "insert into `users` (`id`,`name`,`password`,`email`,`birthday`) values(?,?,?,?,?)";
            pres = con.prepareStatement(sql);
//            此处的sql语句,属于预编译状态,写,但是不执行。

//            手动复制
            pres.setInt(1,5);
            pres.setString(2,"Duan");
            pres.setString(3,"654321");
            pres.setString(4,"Duan@qq.com");
//            注意:Date的类型有多种:
//            sql.Date   -> 数据库,代码java.sql.Date()转化时间。
//            util.Date  -> Java,代码new Date().getTime()用于获得时间戳,
            pres.setDate(5,new java.sql.Date(new Date().getTime()));

//            执行
            int i = pres.executeUpdate();
            if (i > 0) {
                System.out.println("Insert2 Successful!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con,pres,null);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

2.删除-Delete

package com.Edwin.lession03;
import com.Edwin.lession02.Stils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 2:29
 */
public class TestDelete2 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pres = null;

        try {
            con = JdbcUtils.getConnection();

//            PreparedStatement开始于Statement的有区别:
//            使用“?”占位符来代替参数,可以提高效率,
            String sql = "delete from `users` where id = ?";
            pres = con.prepareStatement(sql);
//            此处的sql语句,属于预编译状态,写,但是不执行。

//            手动复制
            pres.setInt(1,5);

//            执行
            int i = pres.executeUpdate();
            if (i > 0) {
                System.out.println("Delete2 Successful!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con,pres,null);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

3.更改-Update

package com.Edwin.lession03;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 5:17
 */
public class TestUpdate2 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pres = null;

        try {
            con = JdbcUtils.getConnection();

//            PreparedStatement开始于Statement的有区别:
//            使用“?”占位符来代替参数,可以提高效率,
            String sql = "update `users` set  `name` = ?  where id = ?";
            pres = con.prepareStatement(sql);
//            此处的sql语句,属于预编译状态,写,但是不执行。

//            手动复制
            pres.setString(1,"爱狗哥");
            pres.setInt(2,1);

//            执行
            int i = pres.executeUpdate();
            if (i > 0) {
                System.out.println("Update2 Successful!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con,pres,null);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

4.查找-Select

package com.Edwin.lession03;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 5:31
 */
public class TestSelect2 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pres = null;
        ResultSet res = null;

        try {
//            连接数据库
            con = JdbcUtils.getConnection();
//            编写Sql
            String sql = "select * from `users` where id = ?";
//            预编译
            pres = con.prepareStatement(sql);
//            传递参数
            pres.setInt(1, 2);
//            执行
            res = pres.executeQuery();
            if (res.next()) {System.out.println("id = " + res.getObject("id"));
                System.out.println("name = " + res.getObject("name"));
                System.out.println("password = " + res.getObject("password"));
                System.out.println("email = " + res.getObject("email"));
                System.out.println("birthday = " + res.getObject("birthday"));
                System.out.println("+_+-+_+-+_+-+_+-+_+-+_+-");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con, pres, res);
        }
    }
}

在这里插入图片描述

5.防范Sql注入问题

package com.Edwin.lession03;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 5:39
 */
public class Sql注入2 {
    public static void main(String[] args) {
//        普通登录
//        login("Edwin","456798");
//        攻击漏洞型登录
        login("'' or 1=1","'' or 1=1");
    }

    //    登录业务
    public static void login(String username, String password) {
        Connection con = null;
        PreparedStatement pres = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。

//        PreparedStatement 防止Sql注入的本质:把传递进来的参数当做字符.
//        传进来的东西会自带一个 '' 包裹起来,再使用之前的 ' 来通过漏洞来进行操作,会被转义。
            String sql = "select * from `users` where `name`=? and `password`=?";

            pres = con.prepareStatement(sql);
            pres.setString(1, username);
            pres.setString(2, password);

            res = pres.executeQuery();//查询完毕返回一个结果集
            while (res.next()) {
                System.out.println("id = " + res.getObject("id"));
                System.out.println("name = " + res.getObject("name"));
                System.out.println("password = " + res.getObject("password"));
                System.out.println("email = " + res.getObject("email"));
                System.out.println("birthday = " + res.getObject("birthday"));
                System.out.println("+_+-+_+-+_+-+_+-+_+-+_+-");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con,pres,res);
        }
    }
}

login(“Edwin”,“456798”);执行效果:

在这里插入图片描述

login("’’ or 1=1","’’ or 1=1");执行效果

在这里插入图片描述

参考文献

《【狂神说Java】MySQL最新教程通俗易懂》
视频连接:https://www.bilibili.com/video/BV1NJ411J79W

2020.05.24

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值