Java数据库操作类Dbservice详解
Java数据库操作类Dbservice详解
在Java开发中,经常需要进行数据库操作。为了提高代码复用性和开发效率,我们可以将常用的数据库操作封装成一个工具类。
本文将介绍一个基于Java语言的数据库操作类Dbservice,包含了添加、保存、更新、删除、分页查询、列表查询等常用的数据库操作方法。
代码实现
package com.ideabobo.model;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import com.ideabobo.service.DatabaseService;
import com.ideabobo.util.Common;
import com.ideabobo.util.GetNowTime;
import com.ideabobo.util.Page;
public class Dbservice {
private DatabaseService databaseService;
public Dbservice(DatabaseService databaseService){
this.databaseService = databaseService;
}
public static String getTableName(String table){
String pre = Common.getProperty('tableprefix');
return pre+table;
}
public String add(Object o,String tableName) throws Exception {
Class c = o.getClass();
Field[] fs = c.getDeclaredFields();
StringBuffer sql = new StringBuffer();
sql.append('insert into ' + tableName);
StringBuffer sql_name = new StringBuffer();
StringBuffer sql_value = new StringBuffer();
for (Field f : fs) {
f.setAccessible(true);
String fieldName = f.getName();
if ('id'.equals(fieldName)) {
continue;
}else if('serialVersionUID'.equals(fieldName)){
continue;
} else {
if (f.getType().getSimpleName().equals('String')) {
sql_name.append(fieldName.toLowerCase() + ',');
String fd='';
if(f.get(o)!=null){
fd = (String) f.get(o);
}
sql_value.append(''' + fd + ''' + ',');
} else {
sql_name.append(f.getName().toLowerCase() + ',');
sql_value.append(f.get(o) + ',');
}
}
}
String names = sql_name.toString().substring(0, sql_name.length() - 1);
String values = sql_value.toString().substring(0,sql_value.length() - 1);
sql.append('(' + names + ')').append(' ').append('values(').append(values).append(');');
System.out.println(sql.toString());
return sql.toString();
}
// 其他方法省略
}
方法详解
1. add(Object o, String tableName)
- 功能:生成插入数据的SQL语句
- 参数:
o:要插入的对象tableName:表名
- 返回值:插入数据的SQL语句
2. save(Object o, String tableName)
- 功能:判断是插入还是更新数据,并生成相应的SQL语句
- 参数:
o:要保存的对象tableName:表名
- 返回值:插入或更新数据的SQL语句
3. update(Object o, String tableName)
- 功能:生成更新数据的SQL语句
- 参数:
o:要更新的对象tableName:表名
- 返回值:更新数据的SQL语句
4. delete(String tableName, Object paras)
- 功能:生成删除数据的SQL语句
- 参数:
tableName:表名paras:删除条件
- 返回值:删除数据的SQL语句
5. getByPage(Page page, String tableName, String sort, String order, String pageNo, String pageSize)
- 功能:分页查询数据
- 参数:
page:分页对象tableName:表名sort:排序字段order:排序方式pageNo:当前页码pageSize:每页记录数
- 返回值:分页对象
6. getByPageSql(Page page, String sql, String sort, String order, String pageNo, String pageSize)
- 功能:执行自定义的分页查询SQL语句
- 参数:
page:分页对象sql:自定义的SQL语句sort:排序字段order:排序方式pageNo:当前页码pageSize:每页记录数
- 返回值:分页对象
7. getByPageLike(Page page, String tableName)
- 功能:模糊查询数据
- 参数:
page:分页对象tableName:表名
- 返回值:分页对象
8. list(String tableName, Object paras, String ordersql)
- 功能:生成查询数据的SQL语句
- 参数:
tableName:表名paras:查询条件ordersql:排序语句
- 返回值:查询数据的SQL语句
总结
本文介绍了一个基于Java的数据库操作类Dbservice,包含了常用的数据库操作方法,并对代码进行了详细解释。
使用该类可以简化数据库操作,提高代码复用性和开发效率。
原文地址: https://www.cveoy.top/t/topic/jn0W 著作权归作者所有。请勿转载和采集!