JDBC

时间:2021-09-24 17:44:53   收藏:0   阅读:32

1.连接配置

首先引入数据库驱动:

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

以mysql8.0版本为例,数据库连接程序编写如下:

 @Test
    public void test() throws ClassNotFoundException, SQLException, IOException {
        // 读取配置文件中信息(读取类路径下配置)
        InputStream is = TestClass.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(is);
        System.out.println(properties);
        System.out.println(properties.getProperty("driverClass"));
        //  driverClass=com.mysql.cj.jdbc.Driver
        //  url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimeZone=UTC
        Class.forName(properties.getProperty("driverClass"));
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);
    }

技术分享图片
Driver在静态代码块中有所配置,当加载此类时,会自动进行注册

2.操作数据库

原文:https://www.cnblogs.com/kanaliya/p/15311015.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!