数据库的连接

加载驱动到项目

 

 

 

数据库的连接1

 

public class Connectiontest {
	
	@Test
       //注解--JUnit
	public void testConnection1() throws SQLException {
		//获取Driver的实现类对象
		Driver driver = new com.mysql.jdbc.Driver();
		 //jdbc:mysql:协议
		 //localhost:ip地址
		//3306:默认端口号
		//test:数据库名称
		String url = "jdbc:mysql://localhost:3306/test";
		//将用户名和密码封装在properties
		Properties info = new Properties(); 
		info.setProperty("user", "root");
		info.setProperty("password", "123456"); 
		Connection conn = driver.connect(url, info);
		System.out.println(conn);
	}
}

 

数据库的连接2 

利用java的反射封装驱动

//方式二:对方式一的迭代:在如下的程序中不出现第三方的API,使得程序具有更好的可移植性
	public void testConnection2() throws Exception {
		//获取实现类对象,使用反射
		Class clazz = Class.forName("com.mysql.jdbc.Driver");
		//获取要连接的数据库
		Driver driver = (Driver) clazz.newInstance();
		String url = "jdbc:mysql://localhost:3306/test";
		//将用户名和密码封装在properties
		Properties info = new Properties(); 
		info.setProperty("user", "root");
		info.setProperty("password", "123456"); 
		Connection conn = driver.connect(url, info);
		System.out.println(conn);
	}
}

数据库的连接3 

使用DriverManager替代Driver

	@Test
	public void testConection3() throws Exception{
		//1.获取Driver的实现类对象
		Class clazz = Class.forName("com.mysql.jdbc.Driver");
		Driver driver = (Driver) clazz.newInstance();
		//提供另外三个链接的基本信息
		String password = "123456";
		String user = "root";
		String url = "jdbc:mysql://localhost:3306/mysql";
		//注册驱动
		DriverManager.registerDriver(driver);
		//获取链接
		Connection conn = DriverManager.getConnection(url, user, password);
	    System.out.println(conn);
	}

数据库的连接4

省略注册驱动部分

//方式四 可以只是加载驱动
		@Test
		public void testConection4() throws Exception{
			//提供另外三个链接的基本信息
			String password = "123456";
			String user = "root";
			String url = "jdbc:mysql://localhost:3306/mysql";
			//1.获取Driver的实现类对象
			 Class.forName("com.mysql.jdbc.Driver");
//			Driver driver = (Driver) clazz.newInstance();
//			//注册驱动
			//DriverManager.registerDriver(driver);
			//获取链接
			Connection conn = DriverManager.getConnection(url, user, password);
		    System.out.println(conn);
		}
	

数据库的连接5

问题:如何读取配置文件!

此种方式的好处:
1.实现了数据与代码的分离。实现了解耦

2.如果需要修改配置文件。可以避免程序重新打包

		//方式5 将数据库连接的四个基本信息写在配置文件中,通过读取配置文件的方式,进行连接
	@Test
	public void testConection5() 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);
	}

  

 

posted on 2022-10-31 17:41  iamnapotato  阅读(7)  评论(0)    收藏  举报