JDBC Detailed Explanation (2): Get Database Connection (Super Detailed Explanation)



foreword

This blogger will use CSDN to record the experience and knowledge he has personally gained and learned on the way to study software development. Interested friends can pay attention to the blogger! Perhaps a person can go fast alone, but a group of people can go farther!

1. Element 1: Driver interface implementation class

1. Driver interface introduction

⭕Interface java.sql.Driveris the interface that all JDBCdrivers need to implement . This interface is provided for use by database vendors, and different database vendors provide different implementations.

⭕ There is no need to directly access the class that implements Driverthe interface , but the driver manager class java.sql.DriverManagercalls these Driverimplementations.

  1. OracleDriver:oracle.jdbc.driver.OracleDriver
  2. mySqlDriver:com.mysql.jdbc.Driver

2. Load and register JDBC driver

⭕ Load the driver: To load JDBCthe driver, you need to call Classthe static method of the class forName(), and pass it the class name of JDBCthe driver
Class.forName("com.mysql.jdbc.Driver");

⭕ Register driver: DriverManagerThe class is the driver manager class, which is responsible for managing the driver

  • Register DriverManager.registerDriver(com.mysql.jdbc.Driver)the driver with

  • Normally, you don't need to DriverManagerexplicitly registerDriver()call the method of the class to register an instance of the driver class, because the Driverdriver class of the interface contains a static code block, and in this static code block, DriverManager.registerDriver()the method is called to register an instance of itself.

The following figure is the source code MySQLof Driverthe implementation class:

insert image description here

2. Element 2: URL

JDBC URLis used to identify a registered driver, and the driver manager URLselects to establish a connection to the database.

The criteria for ⭕ JDBC URLconsists of three parts separated by colons.

protocol:subprotocol:subname

  • protocol : JDBC URLthe protocol in alwaysjdbc
  • Subprotocol : The subprotocol is used to identify a database driver
  • Subname : A way to identify a database. The subname can vary according to different subprotocols, and the purpose of using the subname is to provide enough information for locating the database . Contains the host name (corresponding to the ip address of the server), port number, database name

⭕ Example:

insert image description here

⭕ Several commonly used databases JDBC URL:

  • How to write MySQL connection URL:
    jdbc:mysql://主机名称:mysql服务端口号/数据库名称?参数=值&参数=值

    • Example 1:jdbc:mysql://localhost:3306/xiaolaoshiir
    • Example 2: jdbc:mysql://localhost:3306/xiaolaoshiir?useUnicode=true&characterEncoding=utf8(If the JDBC program is inconsistent with the server-side character set, which will cause garbled characters, you can specify the server-side character set through parameters)
    • Example 3:jdbc:mysql://localhost:3306/atguigu?user=root&password=123456
  • The way to write the connection URL of Oracle 9i:
    jdbc:oracle:thin:@主机名称:oracle服务端口号:数据库名称

    • example:jdbc:oracle:thin:@localhost:1521:xiaolaoshiir
  • How to write the connection URL of SQL Server:
    jdbc:sqlserver://主机名称:sqlserver服务端口号:DatabaseName=数据库名称

    • example:jdbc:sqlserver://localhost:1433:DatabaseName=atguigu

3. Element 3: Username and Password

user, passwordyou can use " 属性名=属性值" key-value pair to tell the database

⭕ You can DriverManagercall getConnection()the method of the class to establish a connection to the database

4. Examples of database connection methods

4.1 Connection method 1

@Test
	public void testConnection1() throws SQLException {
     
     
		// 获取Driver实现类对象
		Driver driver = new com.mysql.jdbc.Driver();

		// url:http://localhost:8080/gmall/keyboard.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", "abc123");

		Connection conn = driver.connect(url, info);

		System.out.println(conn);
	}

Disadvantages: The third-party database explicitly appears in the above codeAPI

4.2 Connection method 2

// 方式二:对方式一的迭代:在如下的程序中不出现第三方的api,使得程序具有更好的可移植性
	@Test
	public void testConnection2() 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";

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

		// 4.获取连接
		Connection conn = driver.connect(url, info);
		System.out.println(conn);

	}

Note: Compared with method 1, reflection instantiation is used here Driver, and the third-party database is not reflected in the code API. It embodies the idea of ​​interface-oriented programming.

4.3 Connection method 3

// 方式三:使用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 = "abc123";

		// 注册驱动
		DriverManager.registerDriver(driver);

		// 获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}

Description: Use DriverManagerto realize the connection to the database. Discover the 4 essential elements necessary to get connected.

4.4 Connection method 4

// 方式四:可以只是加载驱动,不用显示的注册驱动过了。
	@Test
	public void testConnection4() throws Exception {
     
     
		// 1.提供三个连接的基本信息:
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "abc123";
		
		// 2.加载Driver
		Class.forName("com.mysql.jdbc.Driver");
		//相较于方式三,可以省略如下的操作:
//		Driver driver = (Driver) clazz.newInstance();
//		// 注册驱动
//		DriverManager.registerDriver(driver);
		//为什么可以省略上述操作呢?
		/*
		 * 在mysql的Driver实现类中,声明了如下的操作:
		 * static {
				try {
					java.sql.DriverManager.registerDriver(new Driver());
				} catch (SQLException E) {
					throw new RuntimeException("Can't register driver!");
				}
			}
		 */

		// 3.获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}

Note: It is not necessary to explicitly register the driver. Because DriverManagerthere is already a static code block in the source code, the registration of the driver is realized.

4.5 Connection method five (final version)

//方式五(final版):将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
	/*
	 * 此种方式的好处?
	 * 1.实现了数据与代码的分离。实现了解耦
	 * 2.如果需要修改配置文件信息,可以避免程序重新打包。
	 */
	@Test
	public void getConnection5() throws Exception{
     
     
		
		//1.读取配置文件中的4个基本信息
		InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
		
		Properties pros = new Properties();
		pros.load(is);
		
		String user = pros.getProperty("user");
		String password = pros.getProperty("password");
		String url = pros.getProperty("url");
		String driverClass = pros.getProperty("driverClass");
		
		//2.加载驱动
		Class.forName(driverClass);
		
		//3.获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);			
	}

Among them, the configuration file is declared in the src directory of the project: [ jdbc.properties]

user=root
password=abc123
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver

Description: Use the configuration file to save the configuration information, and load the configuration file in the code

Benefits of using configuration files:

⭕ Realized the separation of code and data. If you need to modify the configuration information, you can modify it directly in the configuration file without going deep into the code.
⭕ If you modify the configuration information, the process of recompilation is omitted.

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/125226441