实体类 User:
public class User {
private String id;
private String username;
private String password;
public String getUsername() {
return username;
}
/**
* getter,setter.....
*/
}
自动生成sql类:GenerateSql_Util
/****
* INSERT INTO table(field1,field2) VALUES('value1','value2');
* @param obj 传入要生成的实体,需与数据库表的字段一致
* @return 拼成的insert 语句
*/
public static String getSqlInset(Object obj) {
try {
Class<? extends Object> c = obj.getClass();
//获取所有的字段
Field[] fields = c.getDeclaredFields();
//获取实体的类名,需与表名一致
String tableName = c.getSimpleName();
//生成INSERT INTO table(field1,field2) 部分
StringBuffer sbField = new StringBuffer();
//生成VALUES('value1','value2') 部分
StringBuffer sbValue = 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.getSqlInsert(u));
String updateSql = GenerateSql_Util.getSqlUpdate(u) + " WHERE id = '"+ u.getId()+"';";
System.out.println(updateSql);
}
}
结果:
INSERT INTO user(id,username,password) VALUES('1','u1','p1');
UPDATE user SET id = '1',username = 'u1',password = 'p1' WHERE id = '1';