封装获取connection对象的方法

文章展示了如何在Java中通过JdbcUtils类连接数据库,以及使用Druid连接池进行优化。JdbcUtils加载配置文件获取数据库连接,DruidUtils则通过DruidDataSourceFactory创建数据源。此外,还提供了BaseDao2类用于封装SQL的增删改查操作。
摘要由CSDN通过智能技术生成

获connection链接

//连接数据库的工具类
public class JdbcUtils {
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/jdbc.properties"));
            String driver = properties.getProperty("driver");
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
//数据库配置文件jdbc.properties
driver=com.mysql.jdbc.Driver
//数据库链接url
jdbc.url = jdbc:mysql://localhost:3306/learn?useSSL=false
jdbc.username =root
//数据库密码
jdbc.password =123456

通过druid连接池获取connection链接

public class DruidUtils {
    private static Connection connection;
    static{
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/jdbc.properties"));
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            connection = dataSource.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        return connection;
    }
}

//配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/learn?useSSL=false
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

简单封装修改 和查询数据库的方法

public class BaseDao2 {
    /**
     * 增删改的封装
     * @param sql
     * @param parameters
     * @return
     */
    public int update(String sql, Object[] parameters){
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            int parameterCount = parameterMetaData.getParameterCount();
            if(parameters!=null && parameters.length == parameterCount){
                for (int i = 1; i <= parameterCount; i++) {
                    preparedStatement.setObject(i,parameters[i-1]);
                }
            }
            int num = preparedStatement.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(preparedStatement,connection);
        }
        return 0;
    }
	/**
     * 查询的工具类
     * @param sql
     * @param parameters
     * @param cls
     * @param <T>
     * @return
     */
    public <T> List<T> query (String sql, Object[] parameters, Class<T> cls){
        //1.获取数据库链接
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //将sql语句添加到预处理搬运工对象中
            preparedStatement = connection.prepareStatement(sql);
            //获取sql语句占位符的元数据对象
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            //获取sql语句占位符的元数据的个数
            int parameterCount = parameterMetaData.getParameterCount();
            //判断数组是否为空,数组长度和占位符个数是否一样
            if(parameters!= null && parameters.length == parameterCount ){
                //数组部位空,数组长度和占位符个数一致,将占位符补充完整
                for (int i = 1; i <= parameterCount; i++) {
                    preparedStatement.setObject(i,parameters[i-1]);
                }
            }
            //执行查询的sql语句
            resultSet = preparedStatement.executeQuery();
            //获取查询的字段的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取查询的字段的元数据的个数
            int columnCount = metaData.getColumnCount();
            //创建集合,为了将对象添加到集合中
            ArrayList<T> arrayList = new ArrayList<>();
            while(resultSet.next()){
                //通过反射获取实例对象
                T t = cls.getConstructor(null).newInstance(null);
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    //获取字段的值
                    Object value = resultSet.getObject(columnName);
                    //将数据库取出的字段的值赋值给对象
                    BeanUtils.setProperty(t,columnName,value);
                }
                //将对象添加到集合中
                arrayList.add(t);
            }
            return arrayList.size() != 0 ? arrayList : null;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(resultSet,preparedStatement,connection);
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值