In the past programming, I have been the database connection URL and other information to write dead in DAO, this is actually very bad, one to repeat the code, and secondly, if there is a need for database migration (that is, the database address changes), then the database connection URL and other information must be modified, This requires not only a lot of code modification, but also the recompilation of the software, so that development and maintenance costs become larger.
Now, we can configure the database connection information , the information is recorded in the configuration file (text file), the software by reading the configuration file to obtain relevant information, software installation can be based on different customer needs, modify the configuration file, or if the database needs to be migrated, Also only need to modify the configuration file on the database connection information (not only the database connection information, but also other necessary reuse information to write to the configuration file), the configuration file is generally the properties file, the use of key-value pairs to store configuration information, the database connection information for example:
dbdriver=com.mysql.jdbc.DriverdbUrl=jdbc:mysql://localhost:3306/demo43_j4_up Dbusername=Rootdbpassword=root
We need to write a Java to read the configuration file information, the database connection information for example:
Importjava.io.IOException;ImportJava.io.InputStream;Importjava.util.Properties; Public classPropertiesdemo { Public Static FinalString URL;//called by Propertiesdemo.url. Static{Properties Properties=NewProperties (); Try{ //load the src root directory under jdbc.propertiesInputStream is = Propertiesdemo.class. getClassLoader (). getResourceAsStream ("Jdbc.properties"); Properties.load (IS); }Catch(IOException e) {System.out.println ("Exception from" +propertiesdemo.class. GetName () + ". static{}-----------------"); E.printstacktrace (); } URL=properties.getproperty ("url"); } }
Configuration of database Information