1. 程式人生 > >MySQL-讀取配置檔案的工具類與測試

MySQL-讀取配置檔案的工具類與測試

package JDBCUtil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/*
 * 編寫JDBC的工具類,獲取資料庫的連線
 * 採用讀取配置檔案的方式
 * 讀取配置檔案與獲取連線,最好只執行一次,所以採用static{}
 */
public class JDBCUtilConfig {
	private static Connection con;
	private static String driverClass;
	private static String url;
	private static String username;
	private static String password;

	static {
		try {
			readConfig();
			Class.forName(driverClass);
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			throw new RuntimeException("資料庫連線失敗");
		}
	}

	private  static void readConfig() throws IOException {
		InputStream in = JDBCUtilConfig.class.getClassLoader()
				.getResourceAsStream("database.properties");
		Properties pro = new Properties();
		pro.load(in);
		driverClass = pro.getProperty("driverClass");
		url = pro.getProperty("url");
		username = pro.getProperty("username");
		password = pro.getProperty("password");
	}

	public static Connection getConnection() {
		return con;
	}
}

 使用了工具類之後原來的大量程式碼只有一行.

package demo5;

import java.sql.Connection;

import JDBCUtil.JDBCUtilConfig;

public class JDBCUtilConfigTest {
	public static void main(String[] args) {
		Connection con = JDBCUtilConfig.getConnection();
		System.out.println(con);
	}
}