jdbc数据库连接方式(迭代)

方式五为最终版本

方式一

	@Test
	public void testConnection() throws SQLException {
//		1.获取Driver的实现类对象
		Driver driver =new com.mysql.jdbc.Driver();
		//url:http://localhost:8080/gmail/key.jpg
//		jdbc:mysql:协议
//		localhost:ip地址
//		3306  默认mysql端口号
//		test:test数据库
		String 			              url="jdbc:mysql://localhost:3306/test";
//		将用户名和密码封装在Properties
		Properties info=new Properties();
		
		info.setProperty("user", "root");
		info.setProperty("password","root");
		Connection con=driver.connect(url,info);
		System.out.println(con);
	}

方式二

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

方式三

//	方式三:使用DriverManager替换Driver
	@Test
	public void testConnection3() throws Exception {
		
//		1.获取Driver 实现类对象
		Class clazz=Class.forName("com.mysql.jdbc.Driver");
		Driver driver=(Driver)clazz.newInstance();
		
//		2.提供另外三个连接信息
		String url="jdbc:mysql://localhost:3306/test";
		String user="root";
		String password="root";
//		注册驱动
		DriverManager.registerDriver(driver);
//		获取连接
		Connection con=DriverManager.getConnection(url,user,password);
		System.out.println(con);
	}

方式四

//	方式四:可以只是加载驱动,不用显示的注册驱动了
	@Test
	public void testConnection4() throws Exception {
//	1.提供三个连接的基本信息
		String url="jdbc:mysql://localhost:3306/test";
		String user="root";
		String password="root";
//	2.加载Driver
		Class.forName("com.mysql.jdbc.Driver");
//		相较于方式三,可以省略如下操作
//		Driver driver=(Driver)clazz.newInstance();
//		注册驱动
//		DriverManager.registerDriver(driver);
//		为什么可以:
		
		/*在MySQL的Driver实现类中声明了静态代码块来实现注册驱动
		 * 
		 */
//	3.获取连接
		Connection con=DriverManager.getConnection(url,user,password);
		System.out.println(con);
	}

方式五(最终版本)

//	方式五:将数据库连接需要的4个信息
	/*
	 * 好处:
	 * 1.实现了数据与代码的分离,实现了解耦
	 * 2.如果需要修改配置文件信息,可以避免程序重新打包
	 */
	@Test
	public void getConnection5() throws Exception {
//		1.读取配置文件中的4个基本信息
	InputStream is= JdbcCreat1.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");
//	2.加载驱动
	Class.forName(driverClass);
//	3.获取连接
	Connection con = DriverManager.getConnection(url,user,password);
	System.out.println(con);
	}
}
  • 附带的配置文件

    user=root
    password=root
    url=jdbc:mysql://localhost:3306/test
    driverClass=com.mysql.jdbc.Driver
    
posted on 2021-04-15 10:34  猿木头  阅读(137)  评论(0编辑  收藏  举报