1 import java.util.Iterator; 2 import java.util.Map; 3 import java.util.Set; 4 5 public class SQLUtil { 6 public static String sqlSelect = ""; 7 8 public static String selectQuerySQL(Map<String, Object> map, String tableName) { 9 if (map.isEmpty() || map.size() == 0) { 10 sqlSelect = "select*from" + tableName; 11 } else { 12 sqlSelect = "select*from" + tableName + "where"; 13 Set set = map.keySet(); 14 Iterator iterator = set.iterator(); 15 int index = 0; 16 while (iterator.hasNext()) { 17 String key = (String) iterator.next(); 18 Object value = map.get(key); 19 if (value instanceof String) { 20 value = "‘" + value + "‘"; 21 } 22 index++; 23 if ((index == 1 && map.size() == 1) || map.size() == index) { 24 sqlSelect += key + "=" + value + " "; 25 } else { 26 sqlSelect += key + "=" + value + " " + "and" + " "; 27 } 28 } 29 } 30 System.out.println("待执行的select SQL:"+sqlSelect); 31 return sqlSelect; 32 } 33 public static String insertSQL(Map<String,Object>map){ 34 Iterator<String> iterator = map.keySet().iterator(); 35 StringBuilder sqlTable=new StringBuilder("insert into"); 36 StringBuilder sqlKey=new StringBuilder("("); 37 StringBuilder sqlVaule= new StringBuilder("value("); 38 while (iterator.hasNext()){ 39 String key=iterator.next(); 40 if(map.get(key).toString()==null||map.get(key).toString().length()==0){ 41 iterator.remove(); 42 }else { 43 if (key.equals("tableName")){ 44 sqlTable.append(map.get(key)); 45 }else { 46 sqlKey.append(key+","); 47 sqlVaule.append(map.get(key)+","); 48 } 49 } 50 } 51 sqlTable.append(sqlKey.toString().substring(0,sqlKey.toString().lastIndexOf(","))+")").append(sqlVaule.toString().substring(0,sqlVaule.lastIndexOf(","))+")"); 52 String sql=sqlTable.toString(); 53 System.out.println("待执行的insert SQL:"+sql); 54 return sql; 55 } 56 /*此为以上方法的用法,可以忽略*/ 57 /*public static void main(String[] args) { 58 //调用select的方法 59 Map<String,Object> map=new HashMap<>(); 60 map.put("字段名","具体的值"); 61 String tableName="表名"; 62 System.out.println(selectQuerySQL(map,tableName).toString()); 63 //调用insert的方法 64 Map<String,Object> map=new HashMap<>(); 65 map.put("字段名","具体的值"); 66 map.put("tableName","这里最后添加表名"); 67 String sql = insertSQL(map); 68 PreparedStatement statment = connection.prepareStatement(sql); 69 statment.execute(sql);//这里是执行SQL语句,需要借助JDBCUtil中的Connection得到connection 70 }*/ 71 }
原文地址:https://www.cnblogs.com/wangquanyi/p/11329035.html
时间: 2024-10-22 17:05:03