Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does JDBC get a database connection

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "JDBC how to obtain database connection", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "JDBC how to obtain database connection" bar!

Add MySQL drivers:

Different database vendors will have their own drivers to implement the java.sql.Driver interface. For example, the implementation of mysql is com.mysql.jdbc.Driver. Add the mysql-connector-java- version number-bin.jar to the directory of the corresponding project (if it is a dynamic web project, you need to put the corresponding jar package under the WebRoot directory), right-click add as library (if you are using eclipse, click build path).

After mysql8.0, the full path of the driver should be com.mysql.cj.jdbc.Driver, and it can also run correctly using the original path, but it will output a piece of red text recommended to use the new path at the terminal at run time.

Get the connection:

Driver

Before getting the connection. First, you need to create the object that drives the class, and you can obtain the database connection through the connect () method of the driving class. The parameters of the connect () method are as follows:

Connection connect (String url, java.util.Properties info)

Url is used to identify a driver, and the driver manager selects the correct driver through url. The format of url is: jdbc: subprotocol: subname.

Jdbc is the protocol in JDBC url, and the protocol in JDBC is always jdbc.

Subprotocol: used to identify a database driver, MySQL is mysql.

Subname: identify the database in the same format as host name: Port number / database name

Example: jdbc:mysql://localhost:3306/databasename

Info of type Properties is used to provide the user name (user) and password (password) of the database.

To sum up, we can divide the acquisition of a connection into four steps, namely:

Instantiate the Driver class

Provide url

Provide user name and password through Properties

Call the connect () method of the Driver class to get the connection

The specific implementation code is as follows:

@ Testpublic void testConnection () {try {/ / provides the implementation object of the driver interface class Driver driver = null; driver = new com.mysql.cj.jdbc.Driver (); / / url, indicating the specific data to be operated String url = "jdbc:mysql://localhost:3306/test" / / specify the user name and password Properties pros = new Properties (); pros.setProperty ("user", "root"); pros.setProperty ("password", "root"); / / obtain the connection Connection connect = driver.connect (url, pros) through the connect () method in Driver; System.out.println (connect) } catch (SQLException e) {e.printStackTrace ();}}

One disadvantage of using the above code is that the third-party API is used in the code. We can create the object that drives the class by reflection. The improved code is as follows:

@ Testpublic void testConnection () {try {/ / instantiate Driver String className = "com.mysql.cj.jdbc.Driver"; Class cls = Class.forName (className); Driver driver = (Driver) cls.newInstance (); / / url, indicating the specific data to be operated String url = "jdbc:mysql://localhost:3306/test" / / specify the user name and password Properties pros = new Properties (); pros.setProperty ("user", "root"); pros.setProperty ("password", "root"); / / obtain the connection Connection connect = driver.connect (url, pros) through the connect () method in Driver; System.out.println (connect) } catch (SQLException e) {e.printStackTrace ();}}

DriverManager

To obtain the connection through the getConnection () method of DriverManager, first take a look at the parameter details of this method:

Public static Connection getConnection (String url,String user, String password)

Through the three parameters of this method and the specific path of the driver, we can know that the four elements of obtaining the database connection by this method are:

Url

User name

Password

Driving path

So now the steps to get the connection should be:

Give Ming the four elements of obtaining a database connection

Instantiate Driver

Register driver

Get connection

The specific code is:

@ Testpublic void testConnection () {try {/ / gives the four basic elements of a database connection String url = "jdbc:mysql://127.0.0.1:3306/test"; String driverName = "com.mysql.cj.jdbc.Driver"; String user = "root"; String password = "root" / / instantiate Driver Class cls = Class.forName (driverName); Driver driver = (Driver) cls.newInstance (); / / register driver DriverManager.registerDriver (driver); / / get connection Connection connection = DriverManager.getConnection (url, user, password); System.out.println (connection) } catch (Exception e) {e.printStackTrace ();}}

However, the above methods can still be simplified. Let's first look at the specific implementation of com.mysql.cj.jdbc.Driver:

Public class Driver extends NonRegisteringDriver implements java.sql.Driver {public Driver () throws SQLException {} static {try {DriverManager.registerDriver (new Driver ());} catch (SQLException var1) {throw new RuntimeException ("Can't register driver!");}

You can see the step that there is a registered driver in a static code block in the Driver class, so the driver is registered at the same time when instantiating the Driver class, so the code for registering the driver in the above code can be deleted.

Get the connection through configuration file with DriverManager

We can write the four elements of obtaining the database connection in the configuration file, and first create the configuration file jdbc.properties, which contains:

User=rootpassword=rooturl=jdbc:mysql://localhost:3306/testdriverName=com.mysql.cj.jdbc.Driver

Four elements are obtained by reading the information in the configuration file to obtain the connection. The final code is:

@ Testpublic void testConnection5 () {try {/ / load configuration file / / final version uses Properties pros = new Properties (); InputStream is = ConnectionTest.class.getClassLoader () .getResourceAsStream ("jdbc.properties"); pros.load (is); / / read configuration information String user = pros.getProperty ("user") String password = pros.getProperty ("password"); String url = pros.getProperty ("url"); String driverName = pros.getProperty ("driverName"); / / load driver Class.forName (driverName); / / get connection Connection connection = DriverManager.getConnection (url, user, password); System.out.println (connection) } catch (Exception e) {e.printStackTrace ();}}

When you get the connection to the database in this way, if you need to change the user name and password, you no longer need to modify the code when driving the class or operating the database, you only need to modify the values of the items in the configuration file to achieve the change.

Thank you for your reading, the above is the content of "how to obtain database connection from JDBC". After the study of this article, I believe you have a deeper understanding of how to obtain database connection with JDBC, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report