- I. Introduction:
- 1.JDBC (Java Database Connectivity) is a general SQL database access and operation independent of a specific database management system.
* Common interfaces (a set of API s)
* A standard java class library for accessing database is defined. Using this class library, database resources can be accessed conveniently in a standard way. - 2.JDBC provides a unified way to access different databases and shields developers from some details.
- 3. The goal of JDBC is to enable java programmers to use JDBC to connect to any database system that provides JDBC drivers, so that java programmers do not need to
* Specific databases
* The characteristics of the system have been understood too much to simplify the development process. - 4. You can call the getConnection() method of the DriverManager class to establish a connection to the database.
- 5. JDBC URLs are used to identify a registered driver. The driver manager chooses the positive driver through this url to establish a connection to the database.
- 6. The URL consists of three parts and is separated by colons.
*—— jdbc: < subprotocol >: < subname >
*—— Protocol: The protocol in the JDBC URL is always jdbc.
*—— Subprotocol: Subprotocol used to identify a database driver
*—— Subname: A method of identifying a database. Subnames can be changed according to different subprotocols. The purpose of using subnames is to ask the location database to provide sufficient information.
* For example (there may be some changes between versions of each database):
* Connect to MySQL database: jdbc:mysql://localhost:3306/test
* Connect to the SQL Server database: jdbc:microsoft:sqlserver//localhost:1433;DatabaseName = test
* Connect to Oracle database: jdbc:oracle:thin:@localhost:1521:test - II. Steps
- Prepare to connect Mysql:
- 1. Add the jar file (mysql-connector-java-5.1.26-bin.jar)
- 2. Load to the current classpath (right-click jar file, Builder Path add builder path)
- 3. Create Driver Implementation Class Objects
- 4.Driver implements class object calling connect (url, info) method and returning database connection
There are four ways to connect databases:
1. TesDriver (): This method uses driver to establish connection. It has poor reusability and high coupling, but the code is simple and easy to understand.
2.getConnection(): This method has been modified on the basis of the previous method, but it still establishes the connection through the driver object.
* For example, the url, account and password connected to the database are written in the configuration file, the program reads the configuration file, loads the driver through reflection, and creates the driver object.3.testDriverManager(): This method uses the getConnection() method of the driver management class to establish the connection, and has been modified on the basis of the previous method.
* Modified the load-driven method, because the driver management class is used, so there is no need to create the driver object, reducing the amount of code.4.getDriverManager(): This method is a summary of the above methods, relatively less code, high reusability, low coupling.
The first method is:
/**
* 1.Simple connection to database
* Direct access to the interface is not recommended during use. This is just an exercise demonstration.
* Driver It is an interface from which database vendors must provide an interface to access database connections.
* Steps:
* 1.Creating database-driven objects
* 2.url, user, password to prepare database connection
* 3.The database-driven object calls the connect (url, info) method to establish the connection
*/
@Test
public void testDriver() throws Exception{
//1. Driving
Driver driver = new com.mysql.jdbc.Driver();
//2. Prepare url, account number, password
String url = "jdbc:mysql://127.0.0.1:3306/test";//The test database must be created before it can be connected
Properties info = new Properties();
info.put("user", "root");
info.put("password", "");
//3. Building links
Connection connection = driver.connect(url , info);
System.out.println(connection);
}
The second method:
/**
* 2.By modifying and optimizing the above methods, any database connection can be obtained without changing the source program.
* Solution: Put the database-driven Driver implementation class into a configuration file, which is the class name, url, user, passworld.
*Decoupling of specific database by modifying configuration file.
*Steps:
*1.Prepare fields for url, account, password, and driver full class names
*2.Loading configuration files by reflection
*3.Get the information in the configuration file through getProperty()
*4.Create driver object by reflection (link database needs to use this object, so create it)
*5.Driver object calls connect(jdbcUrl, info) to establish a connection
*/
public Connection getConnection() throws Exception{
//1. Prepare field
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//2. Read the jdbc.properties file under the class path through reflection to get configuration information.
InputStream is = getClass().getClassLoader().
getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
//3. Get the value of each field by getProperty() method and assign it to variables
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
//4. Driver objects are created by reflection, so decoupling can be achieved.
//4_1. Creating Driver Objects
Driver driver = (Driver)Class.forName(driverClass).newInstance();
//4_2. Account password
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
//5. Call the connect method to establish a connection
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}
/**
* Test whether the above methods are correct
* @throws Exception
*/
@Test
public void testGetConnection() throws Exception{
System.out.println(getConnection());
}
The third method is:
/**
* 3.The above methods are modified and optimized again.
* DriverManager It's a driven management class, linked to use
* Steps:
* 1.Ready-driven full class name, url, user, password fields
* 2.Read configuration file information by reflection
* 3.Loading the database driver by reflection (because DriverManager is used, linking the database does not require driver objects, so it does not need to be created)
* 4.Use the getConnection(jdbcUrl, user, password) method of the DriverManager class to establish a connection
*/
@Test
public void testDriverManager() throws Exception{
//1. Prepare field
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//2. Read the jdbc.properties file under the classpath to get configuration information
InputStream is = getClass().getClassLoader().
getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
//3. Driver objects are created by reflection, so decoupling can be achieved.
//3_1. Load the database driver (register a driver)
Class.forName(driverClass);
//4. Call the connect method to establish a connection
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
System.out.println(connection);
}
The fourth method:
/**
* 4.Summary.
* Steps:
* 1.Prepare four strings to link to the database
* 1_1.Create Properties Objects
* 1_2.Get the input stream corresponding to jabc.properties
* 1_3.Loading the input stream corresponding to 1_2
* 1_4.Get specific data (Driver, url, user, password)
* 2.Load the database driver (the corresponding Driver implementation class has registration-driven code blocks)
* 3.Get database links through DriverManager's getConnection() method
*
*/
public Connection getDriverManager() throws Exception{
//1_1. Create Properties objects
Properties properties = new Properties();
//1_2. Get the jdbc.properties input stream
InputStream is = getClass().getClassLoader().
getResourceAsStream("jdbc.properties");
//1_3. Load to transmit input stream
properties.load(is);
//1_4. Get specific information
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driver = properties.getProperty("driver");
//2. Loading database driver
Class.forName(driver);
//3. Get the database link through the getConnection() method of DriverManager and return it
return DriverManager.getConnection(jdbcUrl, user, password);
}
/**
* Test the above methods
*/
@Test
public void testGetConnection1(){
try {
System.out.println(getDriverManager());
} catch (Exception e) {
e.printStackTrace();
}
}
jdbc.properties configuration file
#Connect mysql driver, where? characterEncoding=utf-8 is to prevent scrambling
driver = com.mysql.jdbc.Driver
jdbcUrl = jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
user = root
password =
#Connect SQL Server 2008 driver
#driver = com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbcUrl = jdbc:sqlserver://127.0.0.1:1433;DatabaseName = SIMS
#user = sa
#password = admin