[java]代码库
//数据库的配置文件databases.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://localhost:3306/db_book
jdbc.connection.user=root
jdbc.connection.password=wang000123
//加载连接数据库配置文件的工具类
package cn.it.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//获取数据库连接:完成前两步-加载驱动;获取连接数据库的配置文件连接数据库
public class ConfigManager
{
private static ConfigManager configManager;
//读取配置文件:用到map集合中Hashtable子类Properties类
private static Properties properties = new Properties();//获取该实例
//缺省的构造方法,实例化时加载配置文件,私有是防止外界new
private ConfigManager()
{
String configFile = "databases.properties"; //指定根目录
//properties = new Properties();
InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);//把资源文件读入到流
try
{
properties.load(is);
is.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//向外界提供一个获取的方法
public static ConfigManager getInstance()
{
if(configManager==null)
{
configManager = new ConfigManager();
}
return configManager;
}
//获取配置文件的value
public String getValue(String key)
{
return properties.getProperty(key);
}
}
//获取数据库连接的工具类
package cn.it.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtil
{
private static Connection connection = null;
// 使用静态方法获取连接数据库
public static Connection open()
{
// 拿到具体的数据库连接的属性值
String driver = ConfigManager.getInstance().getValue("jdbc.driver");
String url = ConfigManager.getInstance().getValue("jdbc.connection.url");
String user = ConfigManager.getInstance().getValue("jdbc.connection.user");
String password = ConfigManager.getInstance().getValue("jdbc.connection.password");
//获取数据库相关信息
System.out.println(driver);
System.out.println(url);
System.out.println(password);
System.out.println(user);
try
{
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (Exception e)
{
throw new RuntimeException("数据库连接异常!");
}
return connection;
}
// 关闭数据库
public static void close(Connection conn)
{
if (conn != null)
{
try
{
conn.close();
} catch (SQLException e)
{
throw new RuntimeException("数据库关闭异常!");
}
}
}
// 测试数据库连接
public static void main(String[] args)
{
try{
DatabaseUtil.open();
System.out.println("连接成功");
}catch(Exception e)
{
System.out.println("连接失败!");
throw new RuntimeException("连接数据库异常!");
}
}
}
by: 发表于:2017-08-04 14:56:02 顶(0) | 踩(0) 回复
??
回复评论