java 根据指定条件生成修改sql
public class DynamicUpdateSQL {
public static String generateUpdateSQL(String tableName, Map<String, Object> updateFields, Map<String, Object> whereConditions) {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("UPDATE ").append(tableName).append(" SET ");
for (Map.Entry<String, Object> entry : updateFields.entrySet()) {
if (entry.getValue() != null) {
sqlBuilder.append(entry.getKey()).append(" = ?, ");
}
}
sqlBuilder.setLength(sqlBuilder.length() - 2);
if (!whereConditions.isEmpty()) {
sqlBuilder.append(" WHERE ");
for (Map.Entry<String, Object> entry : whereConditions.entrySet()) {
if (entry.getValue() != null) {
sqlBuilder.append(entry.getKey()).append(" = ? AND ");
}
}
sqlBuilder.setLength(sqlBuilder.length() - 4);
}
return sqlBuilder.toString();
}
public static void main(String[] args) {
String tableName = "employees";
Map<String, Object> updateFields = new HashMap<>();
updateFields.put("salary", 50000);
updateFields.put("department_id", 2);
Map<String, Object> whereConditions = new HashMap<>();
whereConditions.put("employee_id", 101);
whereConditions.put("last_name", "Smith");
String sql = generateUpdateSQL(tableName, updateFields, whereConditions);
System.out.println(sql);
}
}