package DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jidao {
//驱动类的全名
private static final
String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//链接的URL
private static final
String URL="jdbc:sqlserver://localhost\\sqlexpress:1433;DatabaseName=zengshan";
//登录sqlserver的用户名
private static final
String USERNAME="sa";
//登录sqlserver的密码
private static final
String PWD="1234";
//数据库对象声明
private Connection con=null;
private PreparedStatement pst=null;
private ResultSet rs=null;
/**
* 加载驱动,建立连接
*/
private void getConnection() throws ClassNotFoundException,
SQLException {
Class.forName(DRIVER);
con=DriverManager.getConnection(URL,USERNAME,PWD);
}
/**
* 执行查询
* @param sql 执行的sql语句
* @param params Object数组,封装所有的Sql语句参数,顺序与sql语句参数一致
* @return resultset 返回执行后的结果集
*/
public ResultSet execQuery(String sql,Object[] params){
try {
getConnection();
pst=con.prepareStatement(sql);
setPrepareStatementParams(params);
rs=pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return rs;
}
/**
* 执行增加,删除,修改SQL操作
* @param sql 执行的参数化SQL语句
* @param params Object数组,封装所有的Sql语句参数,顺序与sql语句参数一致
* @return int 受影响的行数,-1表示出现异常
*/
public int execUpdate(String sql,Object[] params){
try {
getConnection();
pst=con.prepareStatement(sql);
setPrepareStatementParams(params);
int affectedRows=pst.executeUpdate();
return affectedRows;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll();
}
return -1;
}
/**
* 为PrepareStatementParams设置参数
* @param params 参数数组
* @throws SQLException
*/
private void setPrepareStatementParams(Object[] params)
throws SQLException {
if(params!=null){
for(int i=0;i<params.length;i++){
pst.setObject(i+1, params[i]);
}
}
}
/**
* 关闭connection,preparestatement,result
*/
//关闭数据库链接
public void closeAll() {
try{
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}