设为首页 加入收藏

TOP

工具类之数据库工具类:DBUtil(采用反射机制)(五)
2014-11-24 08:16:23 来源: 作者: 【 】 浏览:18
Tags:工具 数据库 DBUtil 采用 反射 机制
on e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, pstat, conn);
}
return listResult;
}
/**
* 根据给出的Class对象和ID删除相应的数据
*
* @param cla 给出的Class对象
* @param id 给出的ID
*/
public static void delete(Class cla, int id) {
// 拼接SQL语句
String tableName = cla.getName().substring(
cla.getName().lastIndexOf(".") + 1);
String sql = new String("delete from " + tableName + " where id = ");
// 连接数据库
Connection conn = null;
PreparedStatement pstat = null;


try {
conn = DBUtil.getConnection();
pstat = conn.prepareStatement(sql);
pstat.setInt(1, id);
pstat.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
DBUtil.close(null, pstat, conn);
}
}
/**
* 根据给出的Class对象、条件和参数值删除相应的数据
*
* @param cla 给出的Class对象
* @param where 给出的条件
* @param value 给出的条件的参数值
*/
public static void delete(Class cla, String where, Object[] value) {
String tableName = cla.getName().substring(
cla.getName().lastIndexOf(".") + 1);
StringBuffer sql = new StringBuffer("delete from " + tableName + " ");
if (where != null && where.length() > 0) {
sql.append(where);
}
// 连接数据库
Connection conn = null;
PreparedStatement pstat = null;
try {
conn = DBUtil.getConnection();
pstat = conn.prepareStatement(sql.toString());
for (int i = 0; i < value.length; i++) {
pstat.setObject(i + 1, value[i]);
}
pstat.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
DBUtil.close(null, pstat, conn);
}


}
/**
* 根据给出的Class对象清空相应的数据表
*
* @param cla 给出的Class对象
*/
public static void clear(Class cla) {
String tableName = cla.getName().substring(
cla.getName().lastIndexOf(".") + 1);
String sql = new String("delete from " + tableName);


// 连接数据库
Connection conn = null;
PreparedStatement pstat = null;
try {
conn = DBUtil.getConnection();
pstat = conn.prepareStatement(sql.toString());
pstat.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
DBUtil.close(null, pstat, conn);
}
}
/**
* 根据给出的字段名获取相应的get方法
*
* @param name 给出的字段名
* @return 返回相应字段的get方法
*/
private static String getMethodName(String name) {
char[] ch = name.toCharArray();
ch[0] -= 32;
String str = new String(ch);
return "get" + str;
}


/**
* 根据给出的字段名获取相应的set方法
*
* @param name 给出的字段名
* @return 返回相应字段的set方法
*/
private static String setMethodName(String name) {
char[] ch = name.toCharArray();
ch[0] -= 32;
String str = new String(ch);
return "set" + str;
}
}

首页 上一页 2 3 4 5 下一页 尾页 5/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[Mongo]按时间分组统计(时间格式.. 下一篇postgresql数据库配置csv格式日志..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)