數據訪問層

public class BaseDao {sql

//數據庫驅動字符串數據庫

private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";sqlserver

//連接url字符串url

private String url="jdbc:sqlserver://localhost:1433;databaseName=My";server

//數據庫用戶名
private String user="sa";對象

//用戶密碼
private String password="";字符串

//數據庫連接對象get

Connection con=null;io


Statement stmt=null;編譯

//結果集對象
ResultSet rs=null;

 //獲取數據庫鏈接對象

public Connection getConnection(){
if(con==null){

//獲取連接並捕捉異常
try{
Class.forName(driver);//加載jdbc驅動
con=DriverManager.getConnection(url,user,password);
}catch(Exception e){
e.printStackTrace();//異常處理
}
}

return con;//返回鏈接對象
}

 

//關閉數據庫鏈接

public void closeAll(Connection con,Statement stmt,ResultSet rs){
try{
if(rs!=null){//若結果集不爲空
rs.close();//關閉結果集
}
if(stmt!=null){//若Statemet對象不爲空
stmt.close();//關閉Statement對象
}
if(con!=null){//若連接對象不爲空
con.close();//關閉連接對象
}
}catch(Exception e){
e.printStackTrace();//異常處理
}
}

//增刪改的操做

public int exceuteUpdate(String preparedSql,Object...param){
PreparedStatement ps=null;
int num=0;
con=getConnection();
try{
ps=con.prepareStatement(preparedSql);
if(param!=null){
for (int i = 0; i < param.length; i++) {

//爲預編譯sql設置參數
ps.setObject(i+1, param[i]);
}
}
num=ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
closeAll(con,ps,null);
}
return num;
}

public int exceuteSelect(String preparedSql,Object...param){
PreparedStatement ps=null;
int num=0;
con=getConnection();
try{
ps=con.prepareStatement(preparedSql);
if(param.length>0){
for (int i = 0; i < param.length; i++) {
ps.setObject(i+1, param[i]);
}
}
num=ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
closeAll(con,ps,null);
}
return num;
}

}

相關文章
相關標籤/搜索