欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

根据JavaBean生成数据库增删改查的SQL语句

程序员文章站 2022-05-10 12:25:43
...

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入 根据JavaBean生成数据库增删改查的SQL语句。 1,genInsertSQL(Object bean); 2,genUpdateSQL(Object bean); 3,genDeleteSQL(Object bean); 4,genFindAllSQL(String tableName); 5,genFindAllSQL(String

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

根据JavaBean生成数据库增删改查的SQL语句。
1,genInsertSQL(Object bean);
2,genUpdateSQL(Object bean);
3,genDeleteSQL(Object bean);
4,genFindAllSQL(String tableName);
5,genFindAllSQL(String tableName)
import java.io.Serializable;

import java.lang.reflect.Field;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.Hashtable;

import java.util.List;

import com.domain.AG;

/**

* FOR JDBC RUID Operation,This class can generate SQL by parameter of

* Object(update/insert/delete)

* or Class(select)

*

*@category com.util

*@class SQLUtil

*@author zhusheng3@126.com

*@date 2008-6-7 下午04:08:40

*@see

*/

public class SQLUtil

{

private final static String database_table_prefix="database.table.prefix";

private String pkColumnName="SN";

public SQLUtil()

{

//pkColumnName is vary of Table,so mothods which need pkColumn can not use static

this.pkColumnName="SN";

}

public SQLUtil(String pkColumnName)

{

//pkColumnName is vary of Table,so mothods which need pkColumn can not use static

this.pkColumnName=pkColumnName;

}

/**

* @param Object the object for insert

* @return an insert String like below:

* insert into vmm_ag(sn,domainname,modifydate,testDouble)

* values(5,'domainname5',to_date('20080121','YYYYMMDD'),22.4)

*/

public static String genInsertSQL(Object bean)

{

List fields=BeanUtil.getFields(bean);

List values=BeanUtil.getValues2String(bean);

Hashtable fieldsTypes = BeanUtil.getFieldsAndTypes(bean);

//System.out.println("fields.size():"+fields.size()+"--values.size():"+values.size());

if(fields.size() !=values.size())

{

String error="ERROR:genInsertSQL(bean)->fields's size does not match values' size,bean:"+bean+

"\n fields.size():"+fields.size()+"--values.size():"+values.size();

System.err.println(error);

return error;

}

//get database table Name

String tableName=getTableName(bean);

String insertSQL="insert into "+tableName+" (";

for (int i = 0; i

{

//if value of this field is null,then ignore this field

if(values.get(i) !=null)

{

insertSQL+=fields.get(i);

//if not the last field,then add ","

if(i!=fields.size()-1)

{

insertSQL+=",";

}

}

}

insertSQL+=")";

insertSQL+="values (";

for (int j = 0; j

{

String value="";

String typeOfThisField=(String) fieldsTypes.get(fields.get(j));

if(typeOfThisField.equalsIgnoreCase("String"))

{ //when String ,add '' around the string ,like:'tempString'

value="'"+values.get(j)+"'";

}

[1] [2] [3]

根据JavaBean生成数据库增删改查的SQL语句