How to get a database connection:
1. Driver Interface:
? The Java.sql.Driver interface is the interface that all JDBC drivers need to implement. This interface is provided to the database vendors, different database vendors to provide different implementations
? The program does not need to go directly to the implementation of the Driver interface class, but by the driver manager class (Java.sql.DriverManager) to call these Driver Implement
2. Load and register the JDBC driver:
? Loading JDBC drivers need to be called Class static methods for classes forname () , passing it to the loaded JDBC class name of the driver
? DriverManager class is a driver manager class that is responsible for managing drivers
? typically not explicitly called DriverManager Class of Registerdriver () method to register an instance of the driver class because Driver The driver class for the interface contains a static block of code that, in this static code block, invokes the Drivermanager.registerdriver () method to register an instance of itself
3. Establish the connection:
? can call DriverManager Class of getconnection () method to establish a connection to the database
? JDBC URL used to identify a driver that is registered with the driver manager through this URL Select the correct driver to establish a connection to the database.
? JDBC URL The standard consists of three parts, separated by a colon between the parts.
–jdbc:< Sub-protocol >:< Sub-name >
– protocol: the protocol in the jdbc URL is always jdbc
– Sub-protocol: a sub-protocol used to identify a database driver
– child name: A way to identify a database. Sub-names can vary depending on the sub-Protocol, and the purpose of the sub-name is to locate the database to provide sufficient information
Public Connection getconnection () throws exception{
String driverclass = null;
String jdbcurl = null;
String user = null;
String password = null;
InputStream in =
GetClass (). getClassLoader (). getResourceAsStream ("jdbc.properties");
Properties Properties = new properties ();
Properties.load (in);
Driverclass = Properties.getproperty ("Driver");
Jdbcurl = Properties.getproperty ("Jdbcurl");
user = Properties.getproperty ("user");
Password = properties.getproperty ("password");
Creating a Driver object from reflection
Driver Driver =
(Driver) Class.forName (Driverclass). newinstance ();
Properties Info = new properties ();
Info.put ("user", user);
Info.put ("password", password);
Get a database connection through the Driver Connect method
Connection Connection = Driver.connect (Jdbcurl, info);
return connection;
}
@Test
public void Testgetconnection () throws exception{
System.out.println (getconnection ());
}
Jdbc.properties file
Driver=oracle.jdbc.driver.oracledriver
Jdbcurl=jdbc:oracle:thin:@localhost : 1521:ORCL
User=scott
Password=tiger
JDBC gets Oracle database connection (using Driver)