/**
* @author Administrator
* 管理连接工具
*/
public class DBTool {
private static String url;
private static String user;
private static String pwd;
//静态块在加载类时执行一次
static{
//加载连接参数
Properties p =new Properties();
//使用ClassLoader 读取类路径下(classpath/src) 下的文件,得到一个输入流
InputStream is=DBTool.class.getClassLoader().getResourceAsStream("util/db.properties");
System.out.println("读取成功");
try {
//从流中读取数据
p.load(is);
//从p(散列表)中获取4个连接参数
String driver =p.getProperty("driver");
System.out.println("获取成功1");
url=p.getProperty("url");
user=p.getProperty("user");
pwd=p.getProperty("pwd");
System.out.println("获取成功2");
Class.forName(driver);
System.out.println("获取成功3");
} catch (Exception e) {
}
}
/**
* 创建连接
*/
public static Connection getConnection() {
try {
return DriverManager
.getConnection(url,user,pwd);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"创建连接失败", e);
}
}
/**
* 关闭连接
* @param con 被关闭的连接
* @param smt 被关闭的Statement
*/
public static void close(
Connection con, Statement smt) {
try {
if(smt != null) {
smt.close();
}
if(con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"释放资源失败", e);
}
}
public static void main(String[] args) {
Connection con =
DBTool.getConnection();
System.out.println(con);
DBTool.close(con, null);
}
}
写的工具类在连接数据库时抛出异常,无法获取db.properties文件,相关配置文件都正确。经过检查是发现获取不来db.properties的相关路径错误。D:\Users\Workspaces\ MyEclipse 10\OrJDBC01\src\util\db.properties 红色地方多了一个空格导致错误。
* @author Administrator
* 管理连接工具
*/
public class DBTool {
private static String url;
private static String user;
private static String pwd;
//静态块在加载类时执行一次
static{
//加载连接参数
Properties p =new Properties();
//使用ClassLoader 读取类路径下(classpath/src) 下的文件,得到一个输入流
InputStream is=DBTool.class.getClassLoader().getResourceAsStream("util/db.properties");
System.out.println("读取成功");
try {
//从流中读取数据
p.load(is);
//从p(散列表)中获取4个连接参数
String driver =p.getProperty("driver");
System.out.println("获取成功1");
url=p.getProperty("url");
user=p.getProperty("user");
pwd=p.getProperty("pwd");
System.out.println("获取成功2");
Class.forName(driver);
System.out.println("获取成功3");
} catch (Exception e) {
}
}
/**
* 创建连接
*/
public static Connection getConnection() {
try {
return DriverManager
.getConnection(url,user,pwd);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"创建连接失败", e);
}
}
/**
* 关闭连接
* @param con 被关闭的连接
* @param smt 被关闭的Statement
*/
public static void close(
Connection con, Statement smt) {
try {
if(smt != null) {
smt.close();
}
if(con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"释放资源失败", e);
}
}
public static void main(String[] args) {
Connection con =
DBTool.getConnection();
System.out.println(con);
DBTool.close(con, null);
}
}
写的工具类在连接数据库时抛出异常,无法获取db.properties文件,相关配置文件都正确。经过检查是发现获取不来db.properties的相关路径错误。D:\Users\Workspaces\ MyEclipse 10\OrJDBC01\src\util\db.properties 红色地方多了一个空格导致错误。