预处理简单JDBC工具

package Util;

import java.sql.*;

/**
 * @author: zyd
 * @date: 2022/8/20 12:51
 */
public class JDBCUtil {
        public static final String URL="jdbc:mysql://127.0.0.1:3306/z_stugl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
        public static final String USER="root";
        public static final String PASSWORD="123456";
        private static  Connection c;
        private static PreparedStatement p;
        public static int update (String sql, Object[] paramter) throws SQLException, ClassNotFoundException {
             p=getConnection().prepareStatement(sql);
            for (int i = 0; i <paramter.length; i++) {
                p.setObject(i+1, paramter[i]);
            }
            int n=p.executeUpdate();
            return n;
        }
        public static ResultSet select(String sql) throws SQLException, ClassNotFoundException {
             p=getConnection().prepareStatement(sql);
            ResultSet rs=p.executeQuery();
            return rs;
        }

        public static ResultSet select(String sql,Object[] paramter) throws SQLException, ClassNotFoundException {
             p=getConnection().prepareStatement(sql);
            for (int i = 0; i < paramter.length; i++) {
                p.setObject(i+1,paramter[i]);
            }
          ResultSet rs=  p.executeQuery();
            return rs;

        }
        public static void close(Connection c,PreparedStatement p) throws SQLException {
            p.close();
            c.close();

        }
        public static void close(ResultSet rs) throws SQLException {
            close(c,p);
            rs.close();
        }
        public static Connection getConnection() throws SQLException, ClassNotFoundException {
            Class.forName("com.mysql.jdbc.Driver");
            return c= DriverManager.getConnection(URL,USER,PASSWORD);

        }

}

主要原理,看api Connection类,里面铺简单的路(createStatement)容易被sql注入,就创建一条安全的路(prepareStatement),?占位符绝绝子;url加时区和编码的是8以上的jdbc用的,8以下记得删除哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值