Home > Database > Mysql Tutorial > Detailed explanation of mysql example of linking to database through configuration file

Detailed explanation of mysql example of linking to database through configuration file

黄舟
Release: 2017-08-13 10:40:32
Original
1387 people have browsed it

This article mainly introduces the relevant information about mysql connecting to the database through the configuration file. It is mainly the implementation of a single-case Hungry-style database connection method tool class. Friends who need it can refer to it

Mysql links the database through the configuration file

Configuration file jdbc.properties


##MySQL
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///ake?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=1234

##Oracle
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#username=scott
#password=tiger
Copy after login

Let’s talk about it briefly. The configuration file writes the database information of MySQL and Oracle. My database is mysql, so I commented out the Oracle configuration information.

The next step is a singleton (hungry Chinese style) tool class to obtain the database connection method


package Studying.d15;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnUtils {
  private static Connection con = null;

  static{
    try {
      Properties p = new Properties();
      p.load( new FileInputStream("jdbc.properties") );
      String driver = p.getProperty("driver");
      String url = p.getProperty("url");
      String username = p.getProperty("username");
      String password = p.getProperty("password");
      System.out.println(url+","+driver);
      Class.forName(driver);
      con = DriverManager.getConnection(url, username, password);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static Connection getConnection(){
    return con;
  }
}
Copy after login

The above is the detailed content of Detailed explanation of mysql example of linking to database through configuration file. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template