The advantages of using a configuration file to access a database are:
Once written at any time, changes to the database type require only the configuration file to be modified.
Settings for the configuration file:
In the configuration file, Key-value is written in the corresponding way.
Sorry, I've only used these two databases:)
----------Oracle
Jdbc.driver_class=oracle.jdbc.driver.oracledriver//Database driver
Jdbc.connection.url=jdbc:oracle:thin: @localhost: 1521:ORCL//Database address
jdbc.connection.username=c# #wuyong//database name
jdbc.connection.password=//Database Password
-----------MySQL
Jdbc.driver_class=com.mysql.jdbc.driver
Jdbc.connection.url=jdbc:mysql://127.0.0.1:3306/mysql
Jdbc.connection.username=root
Jdbc.connection.password=admin
To read a configuration file:
Use the Load () method of the Properties object to implement the read of the configuration file, using the stream to implement the file read and write operations.
To avoid repeatedly writing code that reads the configuration file, you can create a tool class:
Tool Class-Single-row mode
public class ConfigManager {
Tool classes for reading configuration files (properties files)
private static ConfigManager ConfigManager;
private static properties properties;
This must be private, avoid the external new one ConfigManager object
Private ConfigManager () {
String configfil= "Database.propertise";
Properties=new Properties ();
getClassLoader () Return class loader
//getresourceasstream (Configfil) returns InputStream object
inputstream inputstream=configmanag Er.class.getClassLoader (). getResourceAsStream (Configfil);
try {
properties.load (inputstream);
inputstream.close ();
} catch (IOException e) {
//TODO auto-generated catch block
e.printstacktrace ();
}
}
//Set the number of instantiations by single-column mode
Interface for opening up
public static ConfigManager getinstance () {
if (configmanager==null) {
Configmanager=new ConfigManager ();
return ConfigManager;
}
return ConfigManager;
}
Get the corresponding value value by key
public string getString (string key) {
return Properties.getproperty (key);
}
}
Ways to use the tool class:
Get database connection
public Boolean getconnection () {
read out configuration information
String driver=configmanager.getinstance (). getString ("Jdbc.driver_class");
String url=configmanager.getinstance (). getString ("Jdbc.connection.url");
String username=configmanager.getinstance (). getString ("Jdbc.connection.username");
String password=configmanager.getinstance (). getString ("Jdbc.connection.password");
try {
Loading the JDBC Driver
Class.forName (driver);
Connection=drivermanager.getconnection (URL, username, password);
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
return false;
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
return false;
}
return true;
}
Configuration of the Jdbc.properties file