import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtil {
private static String driverClassName;
private static String url;
private static String username;
private static String password;
static {
//为上面值赋予参数
try {
InputStream in=JdbcUtil.class.getClassLoader().getResourceAsStream("dbcfg.properties");
Properties properties=new Properties();
properties.load(in);
driverClassName=properties.getProperty("driverClassName");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
Class.forName(driverClassName);
} catch (Exception e) {
throw new RuntimeException();
}
}
//获得连接
public static Connection getConnection() throws Exception{
return DriverManager.getConnection(url, username, password);
}
//释放资源
public static void release(ResultSet rs,Statement st,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
}
rs=null;
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
}
st=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
}
conn=null;
}
}
}
用于读取配置文件中的连接。