Prestatement的增、删、改、查

本文档展示了如何使用PreparedStatement进行数据库的增删改查操作,以避免SQL注入问题。通过JDBCUtils工具类连接MySQL数据库,执行预编译SQL语句,填充占位符,并提供通用的方法来实现数据操作。示例代码详细说明了更新、插入和查询操作的实现过程。

Prestatement的增、删、改、查

前言:

​ Statement的弊端:需要拼串sql语句,并存在sql注入问题

​ Prestatement相较于Statement的优点在于可防止SQL注入

源码:

链接:https://pan.baidu.com/s/14Y9mPnCPDX013mCeJK7ydA
提取码:sdfo
复制这段内容后打开百度网盘手机App,操作更方便哦

目录结构

image-20210507213005938

1.配置

1.1连接数据库的配置文件

jdbc.properties

user=root
password=shan5211314..
DB_URL=jdbc:mysql://localhost:3306/test
JDBC_DRIVER=com.mysql.jdbc.Driver

1.2 操作数据库的工具类

utils.JDBCUtils

package com.shan.util;

import com.shan.connection.ConnectionTest;

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

/**
 * @author shan
 * @date 2021/5/7
 * 操作数据库的工具类
 */
public class JDBCUtils {
   
   
    //获取数据库连接
    public static Connection getConnection() throws Exception {
   
   
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String DB_URL = pros.getProperty("DB_URL");
        String JDBC_DRIVER = pros.getProperty("JDBC_DRIVER");

        //2.加载驱动
        Class.forName(JDBC_DRIVER);

        //3.获取连接
        Connection conn = DriverManager.getConnection(DB_URL, user, password);
        return conn;

    }

    //关闭数据库的连接操作
    public static void closeResource(Connection conn, PreparedStatement ps){
   
   
        //资源的关闭
        try {
   
   
            if(ps != null)
                ps.close();
        } catch (SQLException e){
   
   
            e.printStackTrace();
        }
        try {
   
   
            if(conn != null)
                conn.close();
        } catch (SQLException e){
   
   
            e.printStackTrace();
        }

    }
    // 查找的 资源关闭
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet result){
   
   
        //资源的关闭
        try {
   
   
            if(ps != null)
                ps.close();
        } catch (SQLException e){
   
   
            e.printStackTrace();
        }
        try {
   
   
            if(conn != null)
                conn.close();
        } catch (SQLException e){
   
   
            e.printStackTrace();
        }
        try {
   
   
            if(result != null)
                result.close();
        } catch 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值