jdbc获取数据库连接的三种方式

package jdbc1_test;

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

import org.junit.Test;

import com.mysql.cj.jdbc.Driver;

public class Connectiontest {
    //方式一
	@Test
	public void testConnection1() throws Exception {
		//1、获取Driver实现类的对象
		Class clazz=Class.forName("com.mysql.cj.jdbc.Driver");
		Driver driver=(Driver)clazz.newInstance();
		//2、提供另外三个连接的基本信息
		String url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
		String user="root";
		String password="123456";
		//注册驱动
		DriverManager.registerDriver(driver);
		//获取连接
		Connection conn=DriverManager.getConnection(url, user,password);		
		System.out.println(conn);
	}
	//方式二
	@Test
	public void testConnection2() throws Exception {
		
		//1、提供另外三个连接的基本信息
		String url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
		String user="root";
		String password="123456";
		//2、加载Driver
		Class.forName("com.mysql.cj.jdbc.Driver");
		//相较于方式一,可以省略以下操作,在mysql的driver实现类中自动实现了驱动
//		Driver driver=(Driver)clazz.newInstance();	
//		//注册驱动
//		DriverManager.registerDriver(driver);
		//3、获取连接
		Connection conn=DriverManager.getConnection(url, user,password);		
		System.out.println(conn);
	}
	//方式三:最终版
	//将数据库连接需要的这四个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
	@Test
	public void testConnection3() throws Exception {
		
		//读取配置文件中的四个基本信息
		InputStream is=Connectiontest.class.getClassLoader().getResourceAsStream("jdbc.properties");
		
		Properties pro=new Properties();
		pro.load(is);
		
		String user=pro.getProperty("user");
		String password=pro.getProperty("password");
		String url=pro.getProperty("url");
		String driverClass=pro.getProperty("driverClass");
        //加载驱动
		Class.forName(driverClass);
		//获取连接
		Connection conn=DriverManager.getConnection(url, user,password);		
		System.out.println(conn);
	}
}

注:本人因使用php方便所以mysql的端口号使用的是3308

其中,配置文件【jdbc.properties】:此配置文件声明在工程的src下

user=root ;
password=123456 ;
url=jdbc:mysql://localhost:3308/test?rewriteBatchedStatements=true ;
driverClass=com.mysql.jdbc.Driver;

注意:在mysql 8.0版本以后url的设置需要加上进行修改

url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";

驱动driverClass也要修改为

driverClass=com.mysql.cj.jdbc.Driver

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值