关闭

从配置文件里读取数据,实现多数据库连接

2478人阅读 评论(0) 收藏 举报


配置文件:

db.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/itbbs
username=root
password=sa

加载配置文件:

package com.ccl.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class LoadConfig {

	/**
	 * @author chengchanglun
	 * @param args
	 */

	private Properties prop;

	/**
	 * @param path
	 *            as "/db.properties"
	 */
	public LoadConfig(String path) {

		prop = new Properties();

		InputStream in = null;

		try {

			in = getClass().getResourceAsStream(path);

			prop.load(in);

			in.close();

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public String getDriverClass() {

		return prop.getProperty("driverClass");

	}

	public String getURL() {

		return prop.getProperty("url");

	}

	public String getUserName() {

		return prop.getProperty("username");
	}

	public String getPassWord() {

		return prop.getProperty("password");
	}

	public static void main(String args[]) {

		LoadConfig c = new LoadConfig("/db.properties");

		Properties p = new Properties();

	}

}

连接数据库:

package com.ccl.db;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author chengchanglun
 * @category db
 */
public class ConnectionDataBase {

	private static LoadConfig config;

	private static Connection conn = null;

	public ConnectionDataBase() {

		init();

	}

	public static void init() {

		config = new LoadConfig("/db.properties");

	}

	public ConnectionDataBase(String path) {

		config = new LoadConfig(path);

	}

	public static Connection getConnection() {

		init();

		try {

			Class.forName(config.getDriverClass());

			conn = DriverManager.getConnection(config.getURL(),
					config.getUserName(), config.getPassWord());

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}

		return conn;

	}

	public static void main(String[] args) {

		Connection c = ConnectionDataBase.getConnection();

		System.out.println(c);

	}

}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:90480次
    • 积分:1007
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:11篇
    • 译文:0篇
    • 评论:14条
    文章分类
    最新评论