You can use the connection tool to obtain the database, which is convenient and quick.

Source: Internet
Author: User

You can use the connection tool to obtain the database, which is convenient and quick.

According to the preceding connection method, the disadvantage is that if someone wants to change the database, they have to modify the source code and compile the code. In this way, it is not easy for the customer to modify.

Practice: Write a configuration file, write the data on the configuration file, load and modify the file through the class, and then read the corresponding data. In this way, the problem of Database Change can be solved. We only need to modify the configuration file, without the need to change the source code.


Detailed steps:

1. Obtain the connection through the Connection Tool class

In a project, a tool class is usually written to access the database. After that, all database access operations are obtained from the tool class.

There are two ways to implement tool classes:
• Write Data configuration directly in the tool class.
• Write the database configuration in a properties property file. The tool class reads the property file and obtains database parameters row by row.
The second type is recommended.


2. Maintain connection properties through attribute files

Content of db. properties:
# Driver Class Name
Jdbc. driver = com. mysql. jdbc. Driver
# Connection string
Jdbc. url = jdbc: mysql: // localhost: 3306/csdn
# Username used to access the database
Jdbc. user = root
# Database Access Password
Jdbc. password = 123456


Note: In the properties file, the # symbol represents a comment.


3. Load attribute files from the class path

After defining db. properties, you need to find it in the Java program. You can use the method of loading from the class path:

// Location of the property File
String path = "com/daliu/jdbc/db. properties ";
// Obtain the path of the current class and load the specified property File
Properties. load (DBUtil. class. getClassLoader (). getResourceAsStream (path ));

 

Iv. Disconnection

Define a public method to close the connection in the tool class. All applications that access the database share this method. When the function is completed, close the connection.

Protected static void closeConnection (Connection conn ){
If (conn! = Null ){
Try {
Con. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}

 

First, create a java project, import the required package, and create a new configuration file, such:

 

The code of the db. properties file is as follows:

1 jdbc.driver=com.mysql.jdbc.Driver2 jdbc.url=jdbc:mysql://localhost:3306/csdn3 jdbc.user=root4 jdbc.password=123456

 

The DBUtil code is as follows:

Package com. daliu. jdbc; import java. io. inputStream; import java. SQL. connection; import java. SQL. driverManager; import java. util. properties;/*** use the configuration file to configure the JDBC connection class to manage database connections */public class DBUtil {// public static String url to connect to the database; // username used to connect to the database public static String user; // password used to connect to the database public static String pwd; public static String driver; // static block static {try {// read the configuration file Properties prop = new Prope Rties ();/** this method is more recommended in the future. */InputStream is = DBUtil. class. getClassLoader (). getResourceAsStream ("com/daliu/jdbc/db. properties "); prop. load (is); is. close (); // get the driver = prop. getProperty ("jdbc. driver "); // obtain the Address url = prop. getProperty ("jdbc. url "); // obtain the username user = prop. getProperty ("jdbc. user "); // obtain the password pwd = prop. getProperty ("jdbc. password "); // register the driver Class. forName (driver);} catch (Exception e) {e. printStackTrace ();}} /*** Get a Connection ** @ return * @ throws Exception */public static Connection getConnection () throws Exception {try {/** create a database Connection through DriverManager and return */Connection conn = DriverManager. getConnection (url, user, pwd);/** the set Method of ThreadLocal uses the current thread as the key and saves the given value as the value to the internal map. */Return conn;} catch (Exception e) {e. printStackTrace (); // notifies the caller that the Connection creation error throw e;}/*** closes the specified Connection */public static void closeConnection (Connection conn) {try {if (conn! = Null) {conn. close () ;}} catch (Exception e) {e. printStackTrace () ;}/ *** test whether the connection is successful * @ param args * @ throws Exception */public static void main (String [] args) throws Exception {System. out. println (getConnection ());}}

 

Test results:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.