/**
* 工具类
* @author Administrator
*
*/
public class BaseDao {
//驱动地址
private String driver="com.mysql.jdbc.Driver";
//数据库地址
private String url ="jdbc:mysql://localhost:3306/myschool";
//用户名
private String userName="root";
//密码
private String pwd ="111111";
//连接对象
public Connection conn = null;
//执行sql语句的对象
public PreparedStatement pstmt = null;
//结果集对象
public ResultSet rs =null;
/**
* 获取连接的方法
*/
public void getConnection() {
try {
//加载驱动
Class.forName(driver);
//获取连接
conn = DriverManager.getConnection(url,userName,pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 关闭 所有的对象
*/
public void closeAll() {
if(null!=rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null!=pstmt) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null!=conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 增删改 通用方法
* @return
*/
public int executeUpdate(String sql,List<Object> objs) {
//获取连接对象
getConnection();
//受影响行数
int row = 0;
try {
//创建了执行sql语句的对象
pstmt = conn.prepareStatement(sql);
//判断集合是否为空
if(objs!=null) {
//循环添加参数
for (int i = 0; i < objs.size(); i++) {
//设置参数
pstmt.setObject(i+1,objs.get(i));
}
}
//执行并返回受影响行数
row= pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭所有
closeAll();
}
return row;
}
/**
* 查询的通用方法
* @param sql sql语句
* @param objs sql语句的参数
*/
public void executeQuery(String sql,List<Object> objs) {
//获取连接对象
getConnection();
try {
//创建了执行sql语句的对象
pstmt = conn.prepareStatement(sql);
//判断集合是否为空
if(objs!=null) {
//循环添加参数
for (int i = 0; i < objs.size(); i++) {
//设置参数
pstmt.setObject(i+1,objs.get(i));
}
}
//执行并返回 结果集
rs=pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
database.properties配置文件代码
1.driver=com.mysql.jdbc.Driver
2.url=jdbc:mysql://localhost:3306/数据库
3.username=epetadmin
4.password=0000