JDBC获取数据库的五种连接方式(循循渐进)

获取数据库的连接方式(循循渐进)

方式一:
	@Test
	public void testConnection1() throws SQLException {

		// 实例化mysql的驱动
		Driver driver = new Driver();
		// 提供连接信息,包括url,user,password
		String url = "jdbc:mysql://localhost:3306/eancollect";
		Properties info = new Properties();
		info.setProperty("user", "root");
		info.setProperty("password", "0000");

		// 建立连接
		Connection conn = driver.connect(url, info);
		System.out.println(conn);
	}
方式二:使用反射

	@Test
	public void testConnection2() throws Exception {

		// 通过反射动态获取驱动,并实例化
		Class clazz = Class.forName("com.mysql.jdbc.Driver");
		Driver driver = (Driver) clazz.newInstance();

		// 提供连接信息
		String url = "jdbc:mysql://localhost:3306/eancollect";
		Properties info = new Properties();
		info.setProperty("user", "root");
		info.setProperty("password", "0000");

		// 建立连接
		Connection conn = driver.connect(url, info);
		System.out.println(conn);
	}
方式三:使用DriverManger(驱动管理器)替换Driver
	
	@Test
	public void testConnection3() throws Exception {

		// 通过反射动态获取驱动,并实例化
		Class clazz = Class.forName("com.mysql.jdbc.Driver");
		Driver driver = (Driver) clazz.newInstance();

		// 提供连接信息
		String url = "jdbc:mysql://localhost:3306/eancollect";
		String user = "root";
		String password = "0000";

		//注册驱动
		DriverManager.registerDriver(driver);
		
		// 建立连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}
方式四:(优化)使用DriverManger(驱动管理器)替换Driver

可以显式的加载驱动,不用显式的注册驱动,因为Driver中有静态方法,在加载类的时候,就会注册驱动
在这里插入图片描述

	
	@Test
	public void testConnection4() throws Exception {
		
		// 提供连接信息
		String url = "jdbc:mysql://localhost:3306/eancollect";
		String user = "root";
		String password = "0000";

		// 加载驱动
		Class.forName("com.mysql.jdbc.Driver");

		// 建立连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}
方式五(final版):将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接

此种方式的好处?

  1. 实现了数据与代码的分离。实现了解耦
  2. 如果需要修改配置文件信息,可以避免程序重新打包。

配置文件:
在这里插入图片描述

	
	@Test
	public void testConnection5() throws Exception {
		
		//默认是项目下的文件
		FileInputStream fis = new FileInputStream(new File("hello3.txt"));

		//默认是src下的文件
		//InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
		InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
		
		Properties pros = new Properties();
		pros.load(is);
		String url =pros.getProperty("url") ;
		String user =pros.getProperty("user") ;
		String password =pros.getProperty("password") ;
		String driverClass =pros.getProperty("driverClass") ;
		// 加载驱动
		Class.forName(driverClass);
		// 建立连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值