package com.obtk.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据层共用类
*
* @author pengfei.xiong
*
*/
public class BaseDao {
public Connection conn = null;
public PreparedStatement pstmt = null;
public ResultSet rs = null;
/**
* 获得连对象
* 下面中文部分自行修改,其他代码都可以用
* @return 返回连接对象
*/
public Connection getConnection() {
try {
Class.forName("驱动名称");
conn = DriverManager.getConnection(
"数据库url", "用户名", "密码");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭所有对象
*
* @param rs
* 结果集
* @param pstmt
* 执行
* @param conn
* 连接
*/
public void closeAll(ResultSet rs, Statement pstmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行增删改操作
*
* @param sql
* 执行语句
* @param obj
* 参数数组
* @return 返回受影响的行数
*/
public int executeUpdateSQL(String sql, Object[] obj) {
int row = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
if (obj != null) {
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
}
row = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(rs, pstmt, conn);
}
return row;
}
/**
* 执行查询操作
*
* @param sql
* 查询语句
* @param obj
* 参数列表
* @return 返回对象的结果集
*/
public ResultSet executeQuerySQL(String sql, Object[] obj) {
conn = getConnection();
try {
pstmt = conn.prepareStatement(sql);
if (obj != null) {
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
}
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
转载于:https://www.cnblogs.com/xpf1009/p/9227325.html