2.获取数据库连接

JDBC-获取数据库连接

1. 方式一

这种方式在代码中指明了要获取的是Mysql数据库的驱动对象,如果后续切换其他数据库,就需要修改代码。因此在JDBC程序中,尽量不要出现第三方的API。

java 复制代码
	@Test
    public void test1() throws SQLException {
        Driver driver = new com.mysql.cj.jdbc.Driver();
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection connect = driver.connect("jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC", properties);
        System.out.println(connect);
    }

输出结果:

java 复制代码
com.mysql.cj.jdbc.ConnectionImpl@7642df8f

2. 方式二

使用反射的方式创建驱动对象,这里还是获取Mysql的驱动对象,将来如果要切换数据库,驱动可以做成配置项。

java 复制代码
	@Test
    public void test2() throws Exception {
        Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection connect = driver.connect("jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC", properties);
        System.out.println(connect);
    }

3. 方式三

使用DriverManager获取连接,而非之前的Driver。

java 复制代码
	@Test
    public void test3() throws Exception {
        Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
        DriverManager.registerDriver(driver);
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC", properties);
        System.out.println(connection);
    }

4. 方式四

相较于方式三,去掉了"加载并注册驱动"的步骤。

java 复制代码
	@Test
    public void test4() throws SQLException {
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC", properties);
        System.out.println(connection);
    }

因为,mysql的驱动包,可以自动加载驱动类:

并且在驱动类中已经完成了注册:

5. 方式五(推荐)

将数据库连接信息放到配置文件中

java 复制代码
@Test
    public void test5() throws IOException, ClassNotFoundException, SQLException {
        InputStream inputStream = TestGetConnection.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);
    }

jdbc.properties

java 复制代码
user=root
password=root
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC

6. 获取连接和关闭资源的操作,写在公共的类中

java 复制代码
public class JDBCUtils {
    public static Connection getConnection() throws Exception {
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        Class.forName(driver);

        return DriverManager.getConnection(url, user, password);
    }
    public static void close(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        close(connection,statement);
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
相关推荐
云祺vinchin21 小时前
云祺x鼎捷,为制造企业ERP打造双保险
数据库·安全·制造
我滴老baby21 小时前
2026年AI Agent将走向何方?十大趋势深度解析:从多模态融合到自主决策,从端侧部署到具身智能,提前布局下一个万亿级市场
数据库·人工智能·知识图谱
AC赳赳老秦21 小时前
OpenClaw与思维导图工具联动:自动生成工作规划脑图、拆解任务节点,适配职场管理
java·大数据·服务器·数据库·python·php·openclaw
zhishijike1 天前
全国行政区划sql(省市区)
数据库·sql·mysql
KaMeidebaby1 天前
卡梅德生物技术快报|单 B 细胞抗体技术:全犬源单抗制备流程、关键参数与性能验证
前端·数据库·其他·百度·新浪微博
KG_LLM图谱增强大模型1 天前
scHilda:大模型与知识图谱分层融合,突破单细胞分型瓶颈
数据库·人工智能·知识图谱
凯瑟琳.奥古斯特1 天前
力扣3654:二维矩阵连续空位统计
数据结构·数据库·算法·职场和发展
满昕欢喜1 天前
SQL Server的概述与安装
数据库·sqlserver
2501_930707781 天前
使用C#代码在 Excel 中为数据透视表添加筛选器
数据库·数据挖掘·数据分析
TDengine (老段)1 天前
TDengine 数据库创建与参数详解
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据