数据库(DataBase)-Statement&PrepareStatement代码举例解析

Statement对象

格式分析:

Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

1.使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

Statement st = conn.Createstatement() ;
String sql = "insert into uer(...) values(....)";
int num = st.executeUpdate(sql);
if (num>0){
	System.out.println("插入成功!!! ");
}

2.使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

Statement st = conn.Createstatement();
String sql = "delete from user where id=1";
int num = st.executeUpdate(sql) ;
if (num>0){
	System.out.println("删除成功! ! ! ");
}

3.使用executeUpdate(String sql)方法完成数据修改操作,示例操作:

Statement st = conn. createstatement( ;
String sq1 = "update user set name = '' where name = ''";
int num = st.executeUpdate(sql) ;
if (num>0){
	system.out.println(“修改成功! ! ! ");
}

4.使用executeQuery(String sql)方法完成数据查询操作,示例操作:

Statement st = conn.createstatement() ;
String sq1 = "select * from user where id=1";
ResultSet rs = st.executeQuery(sql);// executeUpdate也可
while(rs.next()){
	//根据 获取列的数据类型,分别调用rs的相应方法映射到java对象中
}

代码实现:

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();
            }
        }
    }
}

2.Insert测试
package com.Edwin.lession02;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @author Edwin D
 * @date 2020.5.21 上午 10:36
 */
public class TestInsert {
    public static void main(String[] args) {

        Connection con = null;
        Statement sta = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。
            sta = con.createStatement(); // 获取Sql的执行对象。
            String sql = "insert into `users` (`id`,`name`,`password`,`email`,`birthday`)" +
                    "values" +
                    "(4,'成龙','987654','JackChan@qq.com','1957-07-07');";
            int i = sta.executeUpdate(sql);
            if (i > 0) {
                System.out.println("Insert Successfully!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(con, sta, res);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

3.Delete测试
package com.Edwin.lession02;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @author Edwin D
 * @date 2020.5.21 上午 10:48
 */
public class TestDelete {
    public static void main(String[] args) {

        Connection con = null;
        Statement sta = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。
            sta = con.createStatement(); // 获取Sql的执行对象。
            String sql = "delete from `users` where id = 4;";
            int i = sta.executeUpdate(sql);
            if (i > 0) {
                System.out.println("Delete Successfully!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(con, sta, res);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

4.Update测试
package com.Edwin.lession02;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @author Edwin D
 * @date 2020.5.21 上午 10:52
 */
public class TestUpdate {
    public static void main(String[] args) {
        Connection con = null;
        Statement sta = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。
            sta = con.createStatement(); // 获取Sql的执行对象。
            String sql = "update `users` set `name` = '成果果', `email` = '成果果@qq.com' 
                		where id = 1;";
            int i = sta.executeUpdate(sql);
            if (i > 0) {
                System.out.println("Update Successfully!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(con, sta, res);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

5.Select测试
package com.Edwin.lession02;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * @author Edwin D
 * @date 2020.5.21 上午 11:08
 */
public class TestSelect {
    public static void main(String[] args) {
        Connection con = null;
        Statement sta = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。
            sta = con.createStatement(); // 获取Sql的执行对象。

//        Sql
            String sql = "select * from `users` where id = 1";

            res = sta.executeQuery(sql);//查询完毕返回一个结果集
            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,sta,res);
        }
    }
}

SQL注入问题

sql存在漏洞,容易导致数据泄露

package com.Edwin.lession02;
import com.Edwin.lession02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * @author Edwin D
 * @date 2020.5.21 下午 1:01
 */
public class Sql注入 {

    public static void main(String[] args) {
//        普通登录
//        login("Edwin","456798");
//        攻击漏洞型登录
        login(" ' or '1=1","789123 ' or ' 1=1");
    }
    //    登录业务
    public static void login(String username, String password) {
        Connection con = null;
        Statement sta = null;
        ResultSet res = null;

        try {
            con = JdbcUtils.getConnection(); // 获取数据库连接。
            sta = con.createStatement(); // 获取Sql的执行对象。

//        Sql:select * from `users` where `name` = 'Edwin' and `password` = '123456';
            String sql = "select * from `users` where `name` = '" + username + "' and `password` = '" + password + "'";

            res = sta.executeQuery(sql);//查询完毕返回一个结果集
            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,sta,res);
        }
    }
}

普通登录查询结果:

在这里插入图片描述

利用漏洞的查询结果:

在这里插入图片描述

整个数据库里面的数据都被查了出来,存在着极大的安全隐患。

5.PrepareStatement对象

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

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
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值