JDBC实现对数据库crud操作(Statement和Preparedment简单用法)

一. JDBC实现对数据库crud操作

1. 代码实现查询

1 查询操作

   @Test
    public void testSelect() {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            //1 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2 创建数据库连接
            //第一个参数 url:数据库地址  jdbc:mysql://数据库ip:端口号/数据库名称
            ///  如果连接数据库是本地数据库,并且端口号是3306 简写 jdbc:mysql:///db2
            //第二个参数 user:用户名
            //第三参数 password:密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2","root","root");

            //3 编写sql语句,创建Statement,执行sql语句
            String sql = "select did,dname from dept";
            //创建Statement
            statement = conn.createStatement();
            //statement执行sql语句
            rs = statement.executeQuery(sql);

            //4 查询返回结果集,遍历显示内容
            while(rs.next()) {
//                int did = rs.getInt("did");
                String did = rs.getString("did");
                String dname = rs.getString("dname");
                System.out.println("did: "+did);
                System.out.println("dname: "+dname);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                rs.close();
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

2. 代码实现添加操作

添加操作

//2 添加操作
@Test
public void testInsert() {
    Connection connection = null;
    Statement statement = null;
    try {
        //1 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2 创建数据库连接
        connection = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        //3 编写sql语句,创建statement对象执行sql语句
        String sql = "insert into dept values(4,'外交部')";
        statement = connection.createStatement();
        //执行 executeUpdate方法进行添加操作,返回影响行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);

    }catch (Exception e) {

    }finally {
        //4 关闭资源
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3、代码实现修改和删除操作

删除操作

@Test
public void testDelete() {
    Connection connection = null;
    Statement statement = null;
    try {
        //1 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2 创建数据库连接
        connection = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        //3 编写修改语句,创建statement对象执行修改语句
        String sql = "delete from dept where did=4";
        statement = connection.createStatement();
        int row = statement.executeUpdate(sql);
        System.out.println(row);
    }catch (Exception e) {
    }finally {
        //4 关闭资源
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
修改操作
@Test
public void testUpdate() {
    Connection connection = null;
    Statement statement = null;
    try {
        //1 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2 创建数据库连接
        connection = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        //3 编写修改语句,创建statement对象执行修改语句
        String sql = "update dept set dname='对外交流部' where did=4";
        statement = connection.createStatement();
        int row = statement.executeUpdate(sql);
        System.out.println(row);
    }catch (Exception e) {
    }finally {
        //4 关闭资源
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

二. Statement对象缺点(建议使用PreparedStatement对象)

(1)不能处理Blob类型数据

  • Blob类型是二进制类型
  • 使用Statement不能操作二进制类型数据

(2)sql注入问题

SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的 SQL 语句段或命令,从而利用系统的 SQL 引擎完成恶意行为的做法。对于 Java 而言,要防范 SQL 注入,只要用 PreparedStatement 取代 Statement 就可以了。

  • 模拟登录过程演示sql注入问题
  • 创建用户表
    在这里插入图片描述
    在这里插入图片描述

/**
 * 演示sql注入问题
 */
public class JDBCDemo3 {

    public static void main(String[] args) {
        login("mary' or '1'='1","666");
    }

    //模拟登录的方法
    public static void login(String username,String password) {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

            // select * from users where username='mary' or '1'='1' and password='666'
            //  mary' or '1'='1
            String sql = "select * from users where username='"+username+"' and password='"+password+"'";

            System.out.println(sql);
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);

            while(rs.next()) {
                String usernameValue = rs.getString("username");
                String passwordValue = rs.getString("password");
                System.out.println(usernameValue+"::"+passwordValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
} 

(3)sql语句拼接问题

利用satatement写SQL与语句拼接时,要注意拼接的SQL语句变量要写成这样格式:" +dname+"
否则就会报这样的错误:
在这里插入图片描述

因为这时拼接的语句是这样的:
select * from dept where dname= 安保部
显然这样的SQL语句查询的条件少了双引号

@Test
public void test01() {
    Connection conn = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
        String dname = "安保部";
      // 要这样写 “+ +”
        String sql1 = "select * from dept where dname='安保部'";
        String sql = "select * from dept where dname='"+dname+"'";
        System.out.println(sql);
        statement = conn.createStatement();
        rs = statement.executeQuery(sql);

        while(rs.next()) {
            String did = rs.getString("did");
            String dnameValue = rs.getString("dname");
            System.out.println(did+"::"+dnameValue);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

三. PreparedStatement对象

1、PreparedStatement对象是预编译对象,解决sql注入问题,弥补Statement缺陷

2、执行sql语句时候,把sql语句先进行编译,最后再执行

3、具体使用

在这里插入图片描述

例:预编译模拟登录的方法(preparedStatement增删改操作查)

遍历操作
//预编译模拟登录的方法
public static void loginPrepared(String username,String password) {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        //预编译对象使用过程
        // 使用?代表占位符,需要输入参数
        String sql = "select * from users where username=? and password=?";
        // 创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        // 设置占位符需要值
        // setString两个参数:第一个参数?位置,第二个参数?对应值
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        //执行sql语句
        rs = preparedStatement.executeQuery();

        while(rs.next()) {
            String usernameValue = rs.getString("username");
            String passwordValue = rs.getString("password");
            System.out.println(usernameValue+"::"+passwordValue);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
删除操作
public void test04() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        String sql = "delete from dept where did=?";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setInt(1,100);

        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
修改操作
public void test03() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        String sql = "update dept set dname=? where did=?";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setString(1,"行政部");
        preparedStatement.setInt(2,100);

        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
添加操作
public void test02() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
        String sql = "insert into dept values(?,?)";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setInt(1,100);
        preparedStatement.setString(2,"互动部");
        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
全部代码
//预编译模拟登录的方法
public static void loginPrepared(String username,String password) {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        //预编译对象使用过程
        // 使用?代表占位符,需要输入参数
        String sql = "select * from users where username=? and password=?";
        // 创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        // 设置占位符需要值
        // setString两个参数:第一个参数?位置,第二个参数?对应值
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        //执行sql语句
        rs = preparedStatement.executeQuery();

        while(rs.next()) {
            String usernameValue = rs.getString("username");
            String passwordValue = rs.getString("password");
            System.out.println(usernameValue+"::"+passwordValue);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

//删除
@Test
public void test04() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        String sql = "delete from dept where did=?";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setInt(1,100);

        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

//修改
@Test
public void test03() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");

        String sql = "update dept set dname=? where did=?";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setString(1,"行政部");
        preparedStatement.setInt(2,100);

        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

//添加
@Test
public void test02() {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
        String sql = "insert into dept values(?,?)";
        //创建预编译对象
        preparedStatement = conn.prepareStatement(sql);
        //设置值
        preparedStatement.setInt(1,100);
        preparedStatement.setString(2,"互动部");
        //执行sql
        int row = preparedStatement.executeUpdate();
        System.out.println(row);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值