JDBC--连接数据库的五种方式

这篇博客介绍了Java连接MySQL数据库的五种方法,包括显式使用第三方API、使用反射隐藏API、通过DriverManager注册Driver、利用Driver的静态代码块自动注册以及使用配置文件存储资源信息。每种方法都详细展示了代码实现,强调了逐步优化和提高代码可移植性的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:显式使用第三方api

//jdbc获取数据库连接
public class Connection_use {
    public static void main(String[] args) throws SQLException {
        //com.mysql.cj.jdbc.Driver()
        Driver driver=new com.mysql.cj.jdbc.Driver();
        //jdbc:mysql:协议
        //localhost:ipo地址
        //3306 默认的端口号
        //test :test数据库
//        String url="jdbc:mysql://localhost:3306/test";
       String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC";

        //将用户名和密码封装到 Properties中
        Properties properties=new Properties();
        properties.put("user","root");//用户名
        properties.put("password","1602820115");//密码

        Connection connect = driver.connect(url, properties);
        System.out.println(connect);

    }
}

 方式二:

基于方式一的迭代(使用反射)避免直接出现的三方的api,使得程序具有可移植性(直接修改资源路径即可)
 

//创建数据库连接的方式二,基于方式一的迭代(使用反射)避免直接出现的三方的api,使得程序具有可移植性(直接修改资源路径即可)
public class Connection_use2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, SQLException {
        //获取Driver实现类对象
        String dirverPath="com.mysql.cj.jdbc.Driver";//获取资源路径
        Class<?> aClass = Class.forName(dirverPath);
        //返回空参构造器
        Constructor<?> constructor = aClass.getConstructor();
        //创建Driver对象,这时候强转的类型为Driver接口,可以利用多态将第三方api隐藏
        Driver driver = (Driver) constructor.newInstance();
        //数据库url
        String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC";
        Properties properties=new Properties();
        properties.setProperty("user","root");//用户
        properties.setProperty("password","1602820115");//密码
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);

     }
}

 

//连接数据库方式三,基于方式二的迭代,使用DriverManager类
//连接数据库方式三,基于方式二的迭代
public class Connection_use3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, SQLException {
        //获取Driver对象
        String dirverPath="com.mysql.cj.jdbc.Driver";//获取资源路径
        Class<?> aClass = Class.forName(dirverPath);
        Constructor<?> constructor = aClass.getConstructor();
        Driver driver = (Driver) constructor.newInstance();
        //注册Driver驱动,其实也是封装Driver
        DriverManager.registerDriver(driver);
        //数据库url
        String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC";
        //用户名
        String username="root";
        String password="1602820115";
        //获取连接对象
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);
    }
}

方式四: 

//连接数据库的方式四,基于方式三的优化,mysql的Driver内部有静态代码块自动注册,
// 我们只需要将这个类加载到内存中就可以自动注册

内部的静态代码块

 static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }
//连接数据库的方式四,基于方式三的优化,mysql的Driver内部有静态代码块自动注册,
// 我们只需要将这个类加载到内存中就可以自动注册
public class Connection_use4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, SQLException {
        //数据库url
        String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC";
        //用户名
        String username="root";
        String password="1602820115";
        //获取Driver对象
        String dirverPath="com.mysql.cj.jdbc.Driver";//获取资源路径
        Class<?> aClass = Class.forName(dirverPath);
        //获取连接对象
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);
    }
}

 方式五:使用配置文件存储资源信息

//连接数据库的方式五,基于方式四的优化
//使用Properties配置文件存储资源信息,再读取出来使用
//好处:
//1、实现了数据与代码的分离,实现了解耦
//2、如果需要修改资源信息,可以避免程序重新打包
//3、使得资源信息不再以硬编码的形式暴露在类里面
 

 为了实现流的准确关闭,所以使用了直接处理异常,代码虽然长了一点,但是已经是最终方案

//连接数据库的方式五,基于方式四的优化
//使用Properties配置文件存储资源信息,再读取出来使用
//好处:
//1、实现了数据与代码的分离,实现了解耦
//2、如果需要修改资源信息,可以避免程序重新打包
//3、使得资源信息不再以硬编码的形式暴露在类里面
public class Connection_use5 {
    public static void main(String[] args)  {
        FileInputStream inputStream= null;
        BufferedInputStream inputStream1=null;
        try {
            inputStream = new FileInputStream("src/jdbc.properties");
            inputStream1=new BufferedInputStream(inputStream);
            Properties properties=new Properties();
            properties.load(inputStream1);
            String user = properties.getProperty("user");
            String url = properties.getProperty("url");
            String password = properties.getProperty("password");
            String driverClass = properties.getProperty("DriverClass");
            //注册驱动
            Class.forName(driverClass);
            //获取连接对象
            Connection connection = DriverManager.getConnection(url, user, password);
            System.out.println(connection);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (inputStream1!=null) {
                try {
                    inputStream1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔雀南飞梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值