package Dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
public class BaseDao {
//数据库驱动
public final static String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//链接数据库的地址
public final static String URL="jdbc:sqlserver://localhost:1433;DataBaseName=company";
//数据库用户
public final static String DBNAME="zhaixiaona";
//数据库密码
public final static String DBPASS="zhai123";
public Connection getConn()throws ClassNotFoundException,SQLException{
Class.forName(DRIVER);//注册驱动
//连接数据库
Connection conn=DriverManager.getConnection(URL,DBNAME,DBPASS);
//返回连接
return conn;
}
//释放资源、关闭连接
public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
//如果rs不空,关闭rs。若rs==null则说明就没有打开连接
if(rs!=null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
//如果pstmt不空,关闭pstmt
if(pstmt!=null){
try{
pstmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
//如果conn不空,关闭conn
if(conn !=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
//执行sql语句,可以警醒增、删、改,不能执行查询
public int executeSQL(String preparedSql,String[]param){
Connection conn=null;
PreparedStatement pstmt=null;
int num=0;
try{
conn=getConn();//连接数据库
pstmt=conn.prepareStatement(preparedSql);//对sql语句进行预处理
//判断param是否为空,若为空则直接执行sql语句,若不为空则进行参数化设置
if(param!=null){
for(int i=0;i<param.length;i++){
pstmt.setString(i+1,param[i]);//进行参数化设置
}
}
num=pstmt.executeUpdate();//执行sql语句
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
closeAll(conn,pstmt,null);
}
return num;
}
}