Normally, when we connect to the database via JDBC, the database will not write configuration death, because then there is a database change, it is necessary to repackage deployed to the server or replace the associated .class files, so very inflexible. Therefore, we would typically load the database configuration by reading configuration file way, only this time to change the configuration file can be friends, very convenient.
Directly on the code, here is the java file:
. 1 public class SyncDataFn { 2 . 3 Private static String Driver; . 4 Private static String URL; . 5 Private static String username; . 6 Private static String password; . 7 . 8 static { . 9 the try { 10 // 1. Get the current class by class loader 11 . classLoader = SyncDataFn ClassLoader class .getClassLoader (); 12 is // 2. methods of obtaining a class loader input stream 13 = ClassLoader.getResourceAsStream in the InputStream ( "../ config / jdbc-interface.properties" ); 14 // 3. Create a properties object 15 the Properties The props = new new the Properties (); 16 // 4. Load the input stream . 17 The props. Load (in); 18 is // 5. the acquired for the relevant parameters . 19 Driver = props.getProperty ( "driverClassName" ); 20 is URL = props.getProperty ( "URL" ); 21 is username = props.getProperty ( "username" ) ; 22 is password = props.getProperty ( "password" ); 23 is } catch (IOException e) { 24 e.printStackTrace(); 25 } 26 27 } 28 29 public int jxJson() throws Exception { 30 // 创建Statement用于执行SQL语句 31 Statement stmt = null; 32 String strSQL = ""; 33 Connection connection = null; 34 35 try { 36 Class.forName(driver); 37 connection = DriverManager.getConnection(url, username, password); 38 } catch (ClassNotFoundException e) { 39 e.printStackTrace(); 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 }
Here is the properties file:
1 driverClassName=oracle.jdbc.OracleDriver 2 url=jdbc:oracle:thin:@172.16.35.35:1521:ecard 3 username=ecard 4 password=ecard
There is a pit call classLoader.getResourceAsStream () Gets properties file path when the page get less than the beginning of how, later asked the degree of your mother know that his path is based on the start of .class.
Summary: If you want to get the configuration file, you have to generate the final .class file for the start point, not the path .java file as a starting point, as is the use of real .class file.