Properties(JDBC)连接mysql

properties 文件连接数据库

  1. 创建db.properties文件
#数据库封装成外部文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/j11?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8&useSSL=false
#url=jdbc:mysql://localhost/j11?useSSL=false&CharacterEncoding=UTF-8&server=TUC
user=root
password=19990507

2.创建DButil

package com.xmx.util;

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

//封装数据库的连接
public class DButil {

    private static String drivername;
    private static String url;
    private static String username;
    private static String pwd;

    //静态代码块
    static {
        //1 读 db.properties
        try {
            InputStream is = DButil.class.getClassLoader()
                    .getResourceAsStream("com/xmx/util/db.properties");
            //2 属性集的类
            Properties p = new Properties();
            p.load(is);
            drivername = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("user");
            pwd = p.getProperty("password");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("db.properties 参数出错.....");
        }

    }

    //连接
    public static Connection getConn() {
        try {
            //注册驱动
            Class.forName(drivername);
            //获取连接
            return DriverManager.getConnection(url, username, pwd);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    // 释放是资源
    public static void closeConn(Connection conn, PreparedStatement pst, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值