/**
*
*/
package com.shiguotao.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 数据库连接类 增 删 改 方法
*
* @author 史国涛
*
*/
public class BaseDao {
// j加载驱动
private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 连接数据库地址
//private static final String URL = "jdbc:sqlserver://localhost:1433:DataBaseName=cinema";
private static final String URL = "jdbc:sqlserver://localhost:1433;DataBaseName=cinema";
// 数据库用户
private static final String USER = "sa";
// 数据密码
private static final String PASS = "sa";
/**
* 加载驱动并连接数据
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public Connection getConn() throws SQLException, ClassNotFoundException {
Class.forName(DRIVER);//加载驱动
return DriverManager.getConnection(URL, USER, PASS);//得到连接数据库地址
}
/**
* 关闭所有 连接
*
* @param conn
* 连接数据库
* @param ps
* 执行带参数的SQl语句
* @param rs
* 返货结果集
* @throws SQLException
* 当参数不为空时,并且都是开启的,就把它们关闭
*/
public void closeAll(Connection conn, PreparedStatement ps, ResultSet rs)
throws SQLException {
try {
if (rs != null && !rs.isClosed())
rs.close();
if (ps != null && !ps.isClosed())
ps.close();
if (conn != null && !conn.isClosed())
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
}
/**
* 增删改的方法
* @param sql
* @param param
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public int executteSQL(String sql,Object[] param) throws SQLException, ClassNotFoundException{
Connection conn =null;//声明连接对象
PreparedStatement ps = null;// 声明预编译对象
try {
conn = this.getConn();//加载驱动 连接数据库
ps = conn.prepareStatement(sql);//执行SQL语句
if(param != null){//数组不是空
for(int i = 0; i<param.length;i++){//循环数组
ps.setObject(i+1,param[i]);//给对象设定制定的参数
}
}
int x = ps.executeUpdate();//在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。
return x;//返回x
} finally{
this.closeAll(conn, ps, null);//关比连接
}
}
}