1、使用properties配置文件
開發中獲得連接的4個參數(驅動、url、用戶名、密碼)通常都存放在配置文件中,方便后期維護。程序如果更換數據庫,只需修改配置文件即可。
properties文件的要求:
- 文件位置:建議放在src下
- 文件名稱:擴展名為properties
- 文件內容:格式“key=value”,key可自定義,多個英文單詞.號隔開,value不支持中文
2、創建配置文件
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/jdbctest 3 user=root 4 password=root
3、加載配置文件
加載properties文件獲得流,然后使用properties對象進行處理。
1 package jdbc; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.util.Properties; 8 9 /** 10 * <p> 11 * Description:JDBCUtils工具類 12 * </p> 13 * 14 * @author Administrator 15 * @date 2018年11月4日下午3:03:18 16 */ 17 public class JDBCUtils { 18 private static String driver; 19 private static String url; 20 private static String user; 21 private static String password; 22 // 靜態代碼塊 23 static { 24 try { 25 readConfig(); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 31 // 讀取配置文件 32 private static void readConfig() throws IOException { 33 InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"); 34 Properties prop = new Properties(); 35 prop.load(in); 36 // 使用getProperties(key),通過key獲得需要的值 37 driver = prop.getProperty("driver"); 38 url = prop.getProperty("url"); 39 user = prop.getProperty("user"); 40 password = prop.getProperty("password"); 41 } 42 43 public static Connection getConnection() { 44 try { 45 // 1、注冊驅動 46 Class.forName(driver); 47 // 2、獲得連接 48 Connection conn = DriverManager.getConnection(url, user, password); 49 // 返回連接 50 return conn; 51 } catch (Exception e) { 52 throw new RuntimeException(e); 53 } 54 } 55 }