public class BaseDAO {
private static final String username="root"; //数据库帐号
private static final String password="root"; //数据库密码
private static final String url="jdbc:mysql://localhost:3306/kgcnews"; //数据地址
private static final String driverClassName="com.mysql.jdbc.Driver"; //数据库驱动
protected static Connection connection;
protected static ResultSet resultSet;
protected static PreparedStatement preparedStatement;
//1 获得数据库链接
private static Connection getConnection(){
try {
Class.forName(driverClassName); //step1 加载驱动
connection= DriverManager.getConnection(url,username,password); //step2 使用驱动管理类获得数据库链接
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
return connection;
}
}
//2 通用的增删改的代码
/**
* @param sql
* @param params 可变长度参数(参数可以不赋值 也可以赋多个值),可变长度参数 在参数列表的末尾
* @return
*/
public static int kgcExecuteUpdate(String sql, Object ... params){
int result= 0;
try {
connection=getConnection(); //获得数据库链接
preparedStatement=connection.prepareStatement(sql); //预编译sql语句
//预编译sql语句,给sql语句的参数赋值
if(params!=null &¶ms.length>0){ //判断用户是否传递参数
for(int i=0;i<params.length;i++){
preparedStatement.setObject(i+1,params[i]);
}
}
//执行sql语句
// executeUpdate有一个返回值:这条sql语句在数据库中执行的时候,数据库中有多少条记录被影响
result = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeResource(null,preparedStatement,connection);
}
return result;
}
//3 通用的查询方法
public static ResultSet kgcExecuteQuery(String sql,Object ... params){
try {
connection=getConnection(); //获得数据库链接
preparedStatement=connection.prepareStatement(sql);//预编译sql语句
if(params!=null && params.length>0){ //有参数,给sql语句的参数赋值
for(int i=0;i<params.length;i++){
preparedStatement.setObject(i+1,params[i]);
}
}
resultSet= preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}finally {
return resultSet;
}
}
//4 关闭资源的方法
public static void closeResource(ResultSet rs,PreparedStatement pstmt,Connection con){
try {
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据访问层的通用代码
最新推荐文章于 2021-08-06 10:08:28 发布