数据库连接

25 篇文章 0 订阅

数据库连接

package com.wy;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author HelloWorld
 * @create 2021-05-24-21:57
 * @email 154803771@qq.com
 */
public class MySqlConnect {
	
    // 方法一
    @Test
    public void getConnection1() throws ClassNotFoundException, SQLException {

        // 1.提供连接信息
        String url = "jdbc:mysql://localhost:3306/test";
        String userName = "root";
        String password = "****";

        Properties info = new Properties();
        info.setProperty("user", userName);
        info.setProperty("password", password);


        // 2.获取数据库连接
        Driver driver = new com.mysql.jdbc.Driver();
        Connection connection = driver.connect(url, info);

        System.out.println(connection);

    }
	
	// 方法二
    @Test
    public void getConnection2() throws ClassNotFoundException, SQLException {
        // 1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2.提供连接信息
        String url = "jdbc:mysql://localhost:3306/test";
        String userName = "root";
        String password = "****";
        // 3.获取数据库连接
        Connection connection = DriverManager.getConnection(url, userName, password);

        System.out.println(connection);
    }

	// 方法三
    @Test
    public void getConnection() throws IOException, ClassNotFoundException, SQLException {
        // 1.读取配置文件内容
        InputStream resourceAsStream = MySqlConnect.class.getClassLoader().getResourceAsStream("root1949.properties");

        // 2.数据解析
        Properties properties = new Properties();
        properties.load(resourceAsStream);

        // 3.获取连接信息
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");

        // 4.加载驱动
        Class.forName(driver);

        // 5.连接数据库
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);


    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值