jdbc学习2_statement 和prepareStatement

本文通过两个示例介绍了如何使用 Java 的 JDBC 进行数据库操作,并演示了一个 SQL 注入攻击的例子。首先展示了如何使用 PreparedStatement 插入数据,接着说明了直接拼接 SQL 语句可能导致的安全风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、

    @Test
    public void testPreparedStatement() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
 
        try {
            connection = JDBCTools.getConnection();
            String sql = "INSERT INTO customers (name, email, birth) "
                    + "VALUES(?,?,?)";
 
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "ATGUIGU");
            preparedStatement.setString(2, "simpleit@163.com");
            preparedStatement.setDate(3,
                    new Date(new java.util.Date().getTime()));
 
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTools.releaseDB(null, preparedStatement, connection);
        }
    }
 

 

二、

    /**
     * SQL 注入.
     */
    @Test
    public void testSQLInjection() {
        String username = "a' OR PASSWORD = ";
        String password = " OR '1'='1";
 
        String sql = "SELECT * FROM users WHERE username = '" + username
                + "' AND " + "password = '" + password + "'";
 
        System.out.println(sql);
 
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
 
        try {
            connection = JDBCTools.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
 
            if (resultSet.next()) {
                System.out.println("登录成功!");
            } else {
                System.out.println("用户名和密码不匹配或用户名不存在. ");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTools.releaseDB(resultSet, statement, connection);
        }
    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值