jdbc连接mysql数据库的五种方式

时间:2025-03-20 13:01:46

方式一:

	@Test
	public void testConnection1() throws SQLException {
		// 获取Driver实现类对象
		Driver driver = new ();
		String url = "jdbc:mysql://localhost:3306/test";
		// 将用户名和密码封装在Properties中
		Properties properties = new Properties();
		("user", "root");
		("password", "abc123");

		Connection conn = (url, properties);
		
	}

方式二·:

对方式一的迭代:在如下的程序中不出现第三方的api,使得程序具有更好的可移植性。使用反射》〉》〉》〉》

@Test
	public void testConnection2() throws Exception {
		// 1.获取Driver实现类对象:使用反射
		Class clazz = ("");
		Driver driver = (Driver) ();

		// 2.提供要连接的数据库
		String url = "jdbc:mysql://localhost:3306/test";

		// 3.提供连接需要的用户名和密码
		Properties properties = new Properties();
		("user", "root");
		("password", "abc123");

		// 4.获取连接
		Connection conn = (url, properties);
	}

方式三:

使用DriverManager替换Driver>>>>>>>

@Test
	public void testConnection3() throws Exception {
		// 1.获取Driver实现类的对象
		Class clazz = ("");
		Driver driver = (Driver) ();

		// 2.提供另外三个连接的基本信息:
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "abc123";

		// 注册驱动
		(driver);
		// 获取连接
		Connection conn = (url, user, password);
	}

方式四:

可以只是加载驱动,不用显示的注册驱动过了。

@Test
	public void testConnection4() throws Exception {
		// 1.提供三个连接的基本信息:
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "abc123";
		
		// 2.加载Driver
		("");

		// 3.获取连接
		Connection conn = (url, user, password);
	}

方式五(final版):

将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接

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

配置文件

user=root
password=abc123
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
driverClass=
@Test
	public void getConnection5() throws Exception{
		
		//1.读取配置文件中的4个基本信息
		InputStream inputStream = ().getResourceAsStream("");
		
		Properties properties = new Properties();
		(inputStream);
		
		String user = ("user");
		String password = ("password");
		String url = ("url");
		String driverClass = ("driverClass");
		
		//2.加载驱动
		(driverClass);
		
		//3.获取连接
		Connection conn = (url, user, password);
	}

总结:

jdbc连接数据库的步骤:

  1. 注册驱动
  2. 建立连接(Connection)

当然,我们连接数据库是为了进行数据操作。接下来就是jdbc如何进行数据操作。

@Test
	public void getConnection5() throws Exception{
		
		try {
			//1.读取配置文件中的4个基本信息
			InputStream inputStream = ().getResourceAsStream("");

			Properties properties = new Properties();
			(inputStream);

			String user = ("user");
			String password = ("password");
			String url = ("url");
			String driverClass = ("driverClass");

			//2.加载驱动
			(driverClass);

			//3.获取连接
			Connection conn = (url, user, password);
			//2.预编译sql语句,返回PreparedStatement的实例
			String sql = "update customers set name = ? where id = ?";
			PreparedStatement preparedStatement = (sql);
			//3.填充占位符
			(1,"莫扎特");
			(2, 18);
			//4.执行
			();
		} catch (Exception e) {
			();
		}finally{
			//5.资源的关闭
			();
			();
			
		}
	}