实体类 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);
}
}