Java自动生成insert,update语句_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java自动生成insert,update语句

Java自动生成insert,update语句

 2013/9/29 12:44:18  JoeZe  程序员俱乐部  我要评论(0)
  • 摘要:实体类User:publicclassUser{privateStringid;privateStringusername;privateStringpassword;publicStringgetUsername(){returnusername;}/***getter,setter.....*/}自动生成sql类:GenerateSql_UtilpublicclassGenerateSql_Util{publicstaticStringgetSqlInset(Objectobj){try
  • 标签:Java
实体类 User:
class="java">

public class User {
	private String id;
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	
	/**
	 * getter,setter.....
	 */
	
}

自动生成sql类:GenerateSql_Util
public class GenerateSql_Util {
	public static String getSqlInset(Object obj) {
		try {
			Class<? extends Object> c = obj.getClass();
			Field[] fields = c.getDeclaredFields();
			String tableName = c.getSimpleName();
			StringBuffer sbValue = new StringBuffer();
			StringBuffer sbField = new StringBuffer();
			sbField.append("INSERT INTO " + tableName.toLowerCase() + "(");
			int fieldLength = fields.length;
			for(int i=0;i<fieldLength;i++){
				fields[i].setAccessible(true);
				sbField.append(fields[i].getName().toLowerCase()+',');
				sbValue.append("'"+fields[i].get(obj).toString() +"',");
			}
			return sbField.replace(sbField.length()-1, sbField.length(), ") VALUES(").append(sbValue.replace(sbValue.length()-1, sbValue.length(), ");")).toString();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		return null;
	}
	
	public static String getSqlUpdate(Object obj) {
		try {
			Field[] fields = obj.getClass().getDeclaredFields();
			String tableName = obj.getClass().getSimpleName();
			StringBuffer sb = new StringBuffer();
			sb.append("UPDATE "+ tableName.toLowerCase() +" SET ");
			int fieldLength = fields.length;
			for(int i=0;i<fieldLength;i++){
				fields[i].setAccessible(true);
				sb.append(fields[i].getName() + " = '" + fields[i].get(obj) +"',");
			}
			return sb.replace(sb.length()-1, sb.length(), " ").toString();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		return null;
	}
}

测试代码:注意update的需要加上where条件
public class test {

	public static void main(String[] args) {
		User u = new User();
		u.setId("1");
		u.setUsername("u1");
		u.setPassword("p1");
		System.out.println(GenerateSql_Util.getSqlInset(u));
		String updateSql = GenerateSql_Util.getSqlUpdate(u) + " WHERE id = '"+ u.getId()+"';";
		System.out.println(updateSql);
	}
}
发表评论
用户名: 匿名