数据库连接汇总

本文档展示了如何使用JDBC进行数据库连接,包括加载驱动、创建连接、预编译SQL、执行SQL以及关闭连接。同时,还介绍了数据库连接池的配置与使用,通过DruidDataSourceFactory创建数据源,提高了数据库操作的效率和资源管理。
摘要由CSDN通过智能技术生成

一、通过JDBC完成数据库的连接

1)加载驱动  

2)创建数据库连接对象

3)进行SQL语句的预编译

4)执行SQL语句

5)关闭数据库连接对象

#db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.48.132:3306/book?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
jdbc.user=root
jdbc.password=123456


//定义数据库连接属性
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {
        ResourceBundle rb = ResourceBundle.getBundle("resource.db");
        driver = rb.getString("jdbc.driver");
        url = rb.getString("jdbc.url");
        user = rb.getString("jdbc.user");
        password = rb.getString("jdbc.password");
    }


    //获取连接对象
    public static Connection getConnection(){
        //定义数据库连接对象
        Connection con = null;
        try {
            //加载驱动类
            Class.forName(driver);
            con = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }

    //关闭数据库对象
    public static void closeAll(Connection con, Statement st, ResultSet rs){
        //关闭数据库连接对象
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //关闭命令执行对象
        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //关闭结果集对象
        if(con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //通用设置参数
    public static void setParams(PreparedStatement ps, Object[] params){
        //如果没有参数,这直接返回
        if(params==null)
            return;
        //循环设置参数
        for(int i=0;i< params.length;i++){
            try {
                ps.setObject(i+1,params[i]);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //通用增删改
    public static int executeUpdate(String sql, Object[] params){
        int res = -1;
        //定义数据库连接对象
        Connection con = null;
        //定义预编译命令执行对象
        PreparedStatement ps = null;

        try{
            //获取连接
            con = getConnection();
            //创建预编译命令执行对象
            ps = con.prepareStatement(sql);
            //设置参数
            setParams(ps,params);
            //执行增删给语句,返回数据库硬性的行数
            res = ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭连接对象
            closeAll(con,ps,null);
        }
        return res;
    }

    //通用查询
    public static List<Map> executeQuery(String sql, Object[] params){
        //定义List,存储查询结果(表)
        List<Map> list = new ArrayList<Map>();

        //定义数据库连接对象
        Connection con = null;
        //定义预编译命令执行对象
        PreparedStatement ps = null;
        //定义结果集对象
        ResultSet rs = null;

        try{
            //获取连接对象
            con = getConnection();
            //创建预编译命令执行对象
            ps = con.prepareStatement(sql);
            //设置参数
            setParams(ps,params);
            System.out.println(ps);
            //执行查询操作,返回结果集对象
            rs = ps.executeQuery();

            //获取结果集结构对象
            //rsmd:读取结果集结构
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取查询结果的列数
            int colCount = rsmd.getColumnCount();
            //遍历每一行,封装数据到List
            //rs:读取结果集内容
            while(rs.next()){
                //定义Map存储当前行的个个列
                Map map = new HashMap();
                //循环存储每一列
                for(int i=1;i<=colCount;i++){
                    //获取当前列的列名
                    String colName = rsmd.getColumnName(i);
                    //获取当前列的值
                    Object colValue = rs.getObject(i);
                    //将当前列,存储到Map集合中
                    map.put(colName,colValue);
                }
                //将当前行存储到List中
                list.add(map);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            closeAll(con,ps,rs);
        }
        return list;
    }

    //获取记录的总条数
    public static int getTotalCount(String sqlTotal, Object[] params){
        int count = -1;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try{
            con = getConnection();
            ps = con.prepareStatement(sqlTotal);
            setParams(ps,params);
            rs = ps.executeQuery();
            if(rs.next()){
                //获取查询的单行单列的数据
                count = rs.getInt(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(con,ps,rs);
        }
        return count;
    }

二、数据库连接池

#db.properties
#驱动加载
driverClassName=com.mysql.cj.jdbc.Driver
#注册驱动--192.168.48.132数据库的地址
url=jdbc:mysql://192.168.48.132:3306/book?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
#连接数据库的用户名
username=root
#连接数据库的密码
password=123456
#属性类型的字符串,通过别名的方式配置扩展插件, 监控统计用的stat 日志用log4j 防御sql注入:wall
filters=stat
#初始化时池中建立的物理连接个数。
initialSize=5
#最大的可活跃的连接池数量
maxActive=300
#获取连接时最大等待时间,单位毫秒,超过连接就会失效。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
maxWait=60000
#连接回收器的运行周期时间,时间到了清理池中空闲的连接,testWhileIdle根据这个判断
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
#建议配置为true,不影响性能,并且保证安全性。 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis, 执行validationQuery检测连接是否有效。
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。设置为false
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能,设置为flase
testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。
poolPreparedStatements=false
#池中能够缓冲的preparedStatements语句数量
maxPoolPreparedStatementPerConnectionSize=200


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class BaseDao {

    //定义数据库连接池对象
    private static DataSource dataSource;

    static {
        try {
            InputStream is = BaseDao.class.getResourceAsStream("/db.properties");
            Properties properties = new Properties();
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //获取连接对象
    public static Connection getConnection(){
        //定义数据库连接对象
        Connection con = null;
        try {
            //加载驱动类
            con = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }

    //关闭数据库对象
    public static void closeAll(Connection con, Statement st, ResultSet rs){
        //关闭数据库连接对象
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //关闭命令执行对象
        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //关闭结果集对象
        if(con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //通用设置参数
    public static void setParams(PreparedStatement ps, Object[] params){
        //如果没有参数,这直接返回
        if(params==null)
            return;
        //循环设置参数
        for(int i=0;i< params.length;i++){
            try {
                ps.setObject(i+1,params[i]);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //通用增删改
    public static int executeUpdate(String sql, Object[] params){
        int res = -1;
        //定义数据库连接对象
        Connection con = null;
        //定义预编译命令执行对象
        PreparedStatement ps = null;

        try{
            //获取连接
            con = getConnection();
            //创建预编译命令执行对象
            ps = con.prepareStatement(sql);
            //设置参数
            setParams(ps,params);
            //执行增删给语句,返回数据库硬性的行数
            res = ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭连接对象
            closeAll(con,ps,null);
        }
        return res;
    }

    //通用查询
    public static List<Map> executeQuery(String sql, Object[] params){
        //定义List,存储查询结果(表)
        List<Map> list = new ArrayList<Map>();

        //定义数据库连接对象
        Connection con = null;
        //定义预编译命令执行对象
        PreparedStatement ps = null;
        //定义结果集对象
        ResultSet rs = null;

        try{
            //获取连接对象
            con = getConnection();
            //创建预编译命令执行对象
            ps = con.prepareStatement(sql);
            //设置参数
            setParams(ps,params);
            System.out.println(ps);
            //执行查询操作,返回结果集对象
            rs = ps.executeQuery();

            //获取结果集结构对象
            //rsmd:读取结果集结构
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取查询结果的列数
            int colCount = rsmd.getColumnCount();
            //遍历每一行,封装数据到List
            //rs:读取结果集内容
            while(rs.next()){
                //定义Map存储当前行的个个列
                Map map = new HashMap();
                //循环存储每一列
                for(int i=1;i<=colCount;i++){
                    //获取当前列的列名
                    String colName = rsmd.getColumnName(i);
                    //获取当前列的值
                    Object colValue = rs.getObject(i);
                    //将当前列,存储到Map集合中
                    map.put(colName,colValue);
                }
                //将当前行存储到List中
                list.add(map);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            closeAll(con,ps,rs);
        }
        return list;
    }

    //获取记录的总条数
    public static int getTotalCount(String sqlTotal, Object[] params){
        int count = -1;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try{
            con = getConnection();
            ps = con.prepareStatement(sqlTotal);
            setParams(ps,params);
            rs = ps.executeQuery();
            if(rs.next()){
                //获取查询的单行单列的数据
                count = rs.getInt(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(con,ps,rs);
        }
        return count;
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值