10月9日 Jdbc(2)

news/2024/5/19 1:38:07 标签: intellij-idea, jdbc

PreparedStatement的使用和jdbcUtil工具类的封装

拼接带来的sql注入问题(拼接sql)

Statement

PreparedStatement的使用

package com.fs.db;

import com.fs.util.JdbcUtil;

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

/**
 * 模拟SQL攻击
 */
public class Demo4 {
    public static void main(String[] args) {
        boolean flag = login2("zs", "zs");
        //SQL攻击  SQL注入
        //boolean flag = login2("asdasd' or '1' = '1", "zs' or '1'='1");
        if(flag){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }

    }

    /**
     * 登录方法
     * @param username 用户名
     * @param password 密码
     * @return true登录成功,  false: 登录失败
     */
    public static boolean login(String username,String password){
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&useSSL=false";
            conn = DriverManager.getConnection(url, "root", "123");
            statement = conn.createStatement();

            String sql = "select * from user where username = '"+username+"' and password='"+password+"'";
            System.out.println(sql);
            resultSet = statement.executeQuery(sql);
            return resultSet.next();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            //倒序关
            try {
                if(resultSet != null) {
                    resultSet.close();
                }
                if(statement != null) {
                    statement.close();
                }
                if(conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }


    /**
     *  使用PreparedStatement
     * 登录方法
     * @param username 用户名
     * @param password 密码
     * @return true登录成功,  false: 登录失败
     */
    public static boolean login2(String username,String password){
        Connection conn = null;
        PreparedStatement pstmt  = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&useSSL=false";
            conn = DriverManager.getConnection(url, "root", "123");
            //SQL语句使用?占位
            String sql = "select * from user where username = ?  and password=? ";
            pstmt = conn.prepareStatement(sql);

            //给?赋值setXxx(?序号,值)  从1开始   通用类型: setObject()
            pstmt.setString(1,username);
            pstmt.setString(2,password);

            //执行sql  调用无参的方法
            resultSet =  pstmt.executeQuery();
            return resultSet.next();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            //倒序关
            try {
                if(resultSet != null) {
                    resultSet.close();
                }
                if(pstmt != null) {
                    pstmt.close();
                }
                if(conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }

    /**
     *  使用PreparedStatement
     * 登录方法
     * @param username 用户名
     * @param password 密码
     * @return true登录成功,  false: 登录失败
     */
    public static boolean login3(String username,String password){
        Connection conn = null;
        PreparedStatement pstmt  = null;
        ResultSet resultSet = null;
        try {
           conn = JdbcUtil.getConnection();
            //SQL语句使用?占位
            String sql = "select * from user where username = ?  and password=? ";
            pstmt = conn.prepareStatement(sql);

            //给?赋值setXxx(?序号,值)  从1开始   通用类型: setObject()
            pstmt.setString(1,username);
            pstmt.setString(2,password);

            //执行sql  调用无参的方法
            resultSet =  pstmt.executeQuery();
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
           JdbcUtil.close(conn,pstmt,resultSet);
        }
        return false;
    }

}

和com包同级

jdbc.driverclass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123

Jdbc的工具类 

jdbc的优化  代码重复问题 参数优化问题

第一步:把数据库四大参数放到properties文件
jdbc.driverclass=com.mysql.jdbc.Driver
jdbc.url=jdbc :mysql : / / localhost:3306/test2?
useUnicode=true&characterEncoding=utf8&useSSL=falsejdbc.username=root
jdbc.password=123
第二步:编写一个jdbc的工具类,封装重复代码 (工具类不要让别人可以new出来,所以搞成静态的,返回一个connection对象,直接用类型.属性调用方法和属性)

package com.fs.util;

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

/**
 * JDBC的工具类
 */
public class JdbcUtil {
    private static Properties props = new Properties();
    static{
        //加载db.properties文件
        try {
            //写的绝对路径, 一旦项目拷贝到另外一台电脑,路径可能错误的
            //FileInputStream fis = new FileInputStream("C:\\java6\\jdbc\\code\\demo1\\src\\db.properties");

            //使用相对路径, 相对于src目录
            //getClassLoader()得到该类的类加载器
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
            props.load(in);
            Class.forName(props.getProperty("jdbc.driverclass"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    //得到连接的方法
    public static Connection getConnection() throws SQLException {
        return  DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.username"), props.getProperty("jdbc.password"));
    }

    //关闭资源的方法
    public static void close(Connection conn, PreparedStatement pstmt, ResultSet resultSet){
        try {
            if(resultSet != null) {
                resultSet.close();
            }
            if(pstmt != null) {
                pstmt.close();
            }
            if(conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}

从此用PreparedStatement替代Statement


http://www.niftyadmin.cn/n/5110988.html

相关文章

【数据结构】线性表(九)队列:链式队列及其基本操作(初始化、判空、入队、出队、存取队首元素)

文章目录 一、队列1. 定义2. 基本操作 二、顺序队列三、链式队列0. 链表1. 头文件2. 队列结构体3. 队列的初始化4. 判断队列是否为空5. 入队6. 出队7. 存取队首元素8. 主函数9. 代码整合 堆栈Stack 和 队列Queue是两种非常重要的数据结构,两者都是特殊的线性表&…

[人工智能-综述-15]:第九届全球软件大会(南京)有感 -4-大语言模型全流程、全方面提升软件生产效能

目录 一、软件生产通用模型 1.1 企业软件生产模型 1.2 软件项目管理 VS 软件工程 1.3 企业管理与部门管理 二、第一步:企业数字化:企业信息系统 三、第二步:软件生产自动化:DevOps 四、第四步:软件生产智能化&a…

基于nodejs+vue语言的酒店管理系统

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性:…

自然语言处理---Transformer机制详解之BERT模型特点

1 BERT的优点和缺点 1.1 BERT的优点 通过预训练, 加上Fine-tunning, 在11项NLP任务上取得最优结果.BERT的根基源于Transformer, 相比传统RNN更加高效, 可以并行化处理同时能捕捉长距离的语义和结构依赖.BERT采用了Transformer架构中的Encoder模块, 不仅仅获得了真正意义上的b…

【LeetCode】94. 二叉树的中序遍历 [ 左子树 根结点 右子树 ]

题目链接 文章目录 Python3方法一: 递归 ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯方法二: 迭代 ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯方法三: Morris ⟮ O ( n ) 、 O ( 1 ) ⟯ \lgroup O(n)、O(1) \rgroup ⟮O(n)、O(1)⟯ C…

c++ 网络编程与协议的设计方法

1.TCP协议的粘包问题 TCP协议发送的是字节流,前后之间的间隔在哪里是不确定的,所有有可能出现粘包现象。 解决粘包问题主要有三个办法 (1).发送固定长度的包,这样接受方也接受固定长度,很显然这种办法很死板。 (2).指定字符串…

面向石油和天然气的计算机视觉和深度学习1

面向石油和天然气的计算机视觉和深度学习1 1. 好处1.1 安全1.2 生产优化与估算(Production Optimization and Estimation)1.3 降低生产和维护成本(Reduce Production and Maintenance Costs) 2. 应用2.1 维护2.1.1 预测维护&#…

Ubuntu提示 “unable to find the VMX binary ‘D:\VM17\vmware-vmx.exe‘“

参考:完美解决Unable to find the VMX binary ‘C:\Program Files (x86)\VMware\VMware Workstation\vmware-vmx.exe‘. 1.搜索添加或删除程序,找到VM,点击更改 2.点击修复,等待修复完成就可以了