jdbc篇第6課:使用properties當做Dbc的配置檔案
阿新 • • 發佈:2018-11-28
這節課我們實現一個功能,我們把連線mysql要用到的資訊放在properties配置檔案裡,讓Dbc載入這個檔案讀取配置資訊給我們返回一個Connection物件
實現:
package com.tool; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; //Database Connection,負責連線資料庫,返回一個Connection物件public class Dbc { //不允許呼叫構造器 private Dbc(){} private static Properties properties; private static InputStream inputStream; public static Connection getConnection(String driver,String url,String user, String password) throws ClassNotFoundException, SQLException { Class.forName(driver); return DriverManager.getConnection(url,user,password); } public static ConnectiongetConnection(String propertiesPath) throws IOException, SQLException, ClassNotFoundException { File file = new File(propertiesPath); if (file.getName().endsWith(".properties") && file.exists()) { inputStream = new FileInputStream(file); properties = new Properties(); properties.load(inputStream); String driver = properties.getProperty("driver"); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); return getConnection(driver,url,user,password); } else { throw new FileNotFoundException("cannot find file " + file.getAbsolutePath()); } } }
測試:
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException { Connection conn = Dbc.getConnection("src/com/resource/dbc.properties"); //測試下連線是否真的可用 Statement statement = conn.createStatement(); String sql = "select * from tbl_employee where id = 1"; ResultSet resultSet = statement.executeQuery(sql); resultSet.next(); System.out.println(resultSet.getInt(1)); System.out.println(resultSet.getString(2)); //連線確實可用 }
結果:
1
xiaoye