获取数据库连接对象的方法

public class DBHelper {
private static final String url="jdbc:oracle:thin:@localhost:1521:orcl";//连接字符串
private static final String user="nga";//用户名
private static final String password="123";//密码
private static Connection con =null;
static{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 每次在做数据库操作之前都先获取连接对象
* @throws SQLException
*/
public static void getConnection() throws SQLException{
if(con!=null){
if(con.isClosed()){
con = DriverManager.getConnection(url,user,password);
}
}else{
con = DriverManager.getConnection(url,user,password);
}
}
/**
* 每次用完连接之后就需要关掉
* @throws SQLException
*/
public static void closeConnection() throws SQLException{
if(con !=null){
con.close();
}
}

posted on 2016-09-02 00:24  看你妹儿  阅读(1621)  评论(0编辑  收藏  举报

导航