Java properties file-jdbc optimized programming (5)
Through the configuration file, we can reduce our workload and bring convenience.
Create a properties File
1. Create a New dbconfig. properties. Then add the following code:
driver=com.mysql.jdbc.Driverdburl=jdbc:mysql://localhost:3306/jsp_dbbuser=rootpassword=
Read the rejoice properties File
Create a Properties class and let the load method of the instance of this class read the input stream of the configuration file.
The ConnectionFactory. class. getClassLoader (). getResourceAsStream method is used to obtain the input stream.
Finally, use the getProperties method of the Properties instance to obtain the corresponding property value.
Finally, the singleton design mode is used to set the class instance to static and the constructor to private. GetInstance returns an instance using a static method.
The makeConnection method encapsulates the method for obtaining the Connection.
The Code is as follows:
Public class ConnectionFactory {private static String driver; private static String dburl; private static String user; private static String password; public static ConnectionFactory factory = new ConnectionFactory (); private Connection conn; static {Properties prop = new Properties (); try {InputStream in = ConnectionFactory. class. getClassLoader (). getResourceAsStream ("dbconfig. properties "); prop. load (in);} catch (Exception e) {System. out. println ("========= configuration file read error ============");} driver = prop. getProperty ("driver"); dburl = prop. getProperty ("dburl"); user = prop. getProperty ("user"); password = prop. getProperty ("password"); System. out. println (driver); System. out. println (dburl); System. out. println (user); System. out. println (password);} private ConnectionFactory () {} public static ConnectionFactory getInstance () {return factory;} public Connection makeConnection () {try {Class. forName (driver); conn = (Connection) DriverManager. getConnection (dburl, user, password);} catch (Exception e) {e. printStackTrace () ;}return conn ;}}