Java连接Mysql数据库的5种方法

参考资料:https://www.bilibili.com/video/av69222697?p=63

前言

本文讲述了Java连接Mysql数据库的5种方法,其中最后一种方式是需要掌握的。

1 使用第三方库Driver

@Test
    public void connectionTest01() throws SQLException {
        // 获取Driver实现类对象
        Driver driver = new com.mysql.jdbc.Driver();
        // jdbc:mysql :协议
        // localhost: ip地址
        // 3306 :mysql端口号
        // test :数据库名
        String url = "jdbc:mysql://10.211.55.3:3306/test";
        // 将用户名和密码封装在Properties中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");

        Connection conn = driver.connect(url, info);
        // 如果打印成功,说明连接成功
        System.out.println(conn);
    }

第一种方式用到了第三方库com.mysql.jdbc.Driver,这个包是需要去mysql官网下载、导入的。

2 使用反射

使用反射实例化Driver,不在代码中体现第三方数据库的API,使得程序具有良好的移植性,体现了面向接口编程的思想。

@Test
    public void connectionTest02() throws Exception{
        // 1.获取Driver实现类对象:使用反射
        Class clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver con = (Driver) clazz.newInstance();

        // 2.mysql的地址,用户名和密码
        String url = "jdbc:mysql://10.211.55.3:3306/test";
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","root");

        Connection connect = con.connect(url, info);
        System.out.println(connect);

    }

3 使用DriverManager

使用DriverManager实现数据库的连接。体会获取连接必要的4个基本要素。

 /**
     * 创建数据库连接的第三中方式
     * 使用DriverManager实现数据库的连接。体会获取连接必要的4个基本要素。
     */
    @Test
    public void connectiontest03() throws Exception {
        // 1.数据库连接四要素
        String url = "jdbc:mysql://localhost:3307/test?autoReconnect=true&useSSL=false";
        String username = "root";
        String password = "root";
        String driverName = "com.mysql.jdbc.Driver";

        // 2.实例化Driver
        Class clazz = Class.forName(driverName);
        Driver o = (Driver) clazz.newInstance();

        // 3.注册驱动
        DriverManager.registerDriver(o);

        // 获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);

    }

4 自动注册

driver.class类中的静态代码块在类加载的时候被执行,实现了自动注册。相比方式3免去了自动注册
在这里插入图片描述

 @Test
    public void connectionTest04() throws Exception{
        // 1.数据库连接四要素
        String url = "jdbc:mysql://localhost:3307/test?useSSL=false";
        String username = "root";
        String password = "root";
        String driverName = "com.mysql.jdbc.Driver";
        
        // 将Driver类加载到内存中
        Class.forName(driverName);

        // 2.实例化Driver
//        Class clazz = Class.forName(driverName);
//        Driver o = (Driver) clazz.newInstance();
        // 3.注册驱动
//        DriverManager.registerDriver(o);
        //以上代码被注释的原因:在Driver.class中有如下代码,
        // 在类加载的时候静态代码块被执行
        /**
         * static {
         *                 try {
         *                     DriverManager.registerDriver(new Driver());
         *                 } catch (SQLException var1) {
         *                     throw new RuntimeException("Can't register driver!");
         *                 }
         *             }
         */

        // 获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);
    }

5 使用配置文件

在方式四的基础上使用配置文件的方式保存配置信息(user,password,url,driverClass),在代码中加载配置文件。
在IDEA的相对路径下创建jdbc.properites
在这里插入图片描述

user=root
password=root
url=jdbc:mysql://localhost:3307/test/?useSSL=false
driverName=com.mysql.jdbc.Driver
 @Test
    public void connectionTest05() throws Exception {
        // 1.加载配置文件
        InputStream ras = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties props = new Properties();
        props.load(ras);

        // 2.读取配置文件信息
        String user= props.getProperty("user");
        String password= props.getProperty("password");
        String url= props.getProperty("url");
        String driverClass= props.getProperty("driverClass");

        // 3.加载驱动
        Class.forName(driverClass);

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

使用配置文件的好处:

①实现了代码和数据的分离,如果需要修改配置信息,直接在配置文件中修改,不需要深入代码
②如果修改了配置信息,省去重新编译的过程。

最后一种方式需要掌握,前四种方式了解即可。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Java连接MySQL数据库方法: 1. 使用JDBC连接MySQL数据库 ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySQLConnection { public static void main(String[] args) { // JDBC连接MySQL数据库的URL String url = "jdbc:mysql://localhost:3306/hsp_db02"; // 数据库用户名和密码 String username = "your_username"; String password = "your_password"; try { // 加载MySQL的JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection connection = DriverManager.getConnection(url, username, password); // 连接成功后的操作 System.out.println("成功连接MySQL数据库"); // 关闭数据库连接 connection.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 2. 使用连接连接MySQL数据库(推荐) ```java import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; public class MySQLConnectionPool { public static void main(String[] args) { // 创建连接池对象 BasicDataSource dataSource = new BasicDataSource(); // 设置连接池属性 dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/hsp_db02"); dataSource.setUsername("your_username"); dataSource.setPassword("your_password"); try { // 从连接池获取数据库连接 Connection connection = dataSource.getConnection(); // 连接成功后的操作 System.out.println("成功连接MySQL数据库"); // 关闭数据库连接 connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值