JdbcUtil.java
package com.yi.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JdbcUtil {
//数据库连接url、账号信息默认值
private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
private static String user = "scott";
private static String password = "root";
private static String driverName = "oracle.jdbc.OracleDriver";
//获取配置文件内容
private static ResourceBundle rb = ResourceBundle.getBundle("com/yi/util/jdbc");
static{
//读取配置文件中的字符串
if(!"".equals(rb.getString("url"))){
url=rb.getString("url");
}
if(!"".equals(rb.getString("user"))){
user = rb.getString("user");
}
if(!"".equals(rb.getString("password"))){
password = rb.getString("password");
}
if(!"".equals(rb.getString("driverName"))){
driverName = rb.getString("driverName");
}
try {
// 类加载时就加载驱动
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取默认的连接对象
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//采用提供的连接信息获取连接对象
public static Connection getConnection(String url,String user,String password){
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//关闭资源
public static void close(Connection con,Statement stm,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
if(stm!=null){
stm.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
jdbc.properties
url=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=root
driverName=oracle.jdbc.OracleDriver