org.fingertip.simpledao.utils.SqlBuilder Maven / Gradle / Ivy
The newest version!
package org.fingertip.simpledao.utils;
import org.fingertip.simpledao.bean.SqlFormatResult;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
public class SqlBuilder {
public static SqlFormatResult formatSql(String sql, Object... args){
SqlFormatResult result = new SqlFormatResult();
int len = args.length;
Map map = new TreeMap<>();
if(len == 0){
result.setSql(sql);
result.setArgs(args);
return result;
}
for (int i = 1; i <= len; i++) {
String flag = "?" + i;
int fromIndex = 0;
while(true){
int index = sql.indexOf(flag, fromIndex);
if(-1 != index){
fromIndex = index + 1;
map.put(index,args[i - 1]);
}else{
break;
}
}
sql = sql.replace(flag, "?");
}
result.setSql(sql);
result.setArgs(map.values().toArray());
return result;
}
public static String buildInsertSql(String tableName,Collection dbFieldNames,int entitySize){
StringBuilder sql = new StringBuilder();
StringBuilder marks = new StringBuilder();
sql.append("insert into ");
sql.append(tableName);
sql.append(" (");
for(String dbFieldName : dbFieldNames){
sql.append(dbFieldName);
sql.append(",");
marks.append("?,");
}
sql.deleteCharAt(sql.length() - 1);
marks.deleteCharAt(marks.length() - 1);
sql.append(") ");
sql.append("values ");
for(int i = 0;i < entitySize;i++){
sql.append("(");
sql.append(marks.toString());
sql.append("),");
}
sql.deleteCharAt(sql.length() - 1);
return sql.toString();
}
public static String buildUpdateSql(String tableName, Collection dbFieldNames,String idName) {
StringBuilder sql = new StringBuilder();
sql.append("update ");
sql.append(tableName);
sql.append(" set ");
for(String dbFieldName : dbFieldNames){
sql.append(dbFieldName);
sql.append(" = ?,");
}
sql.deleteCharAt(sql.length()-1);
sql.append(" where ");
sql.append(idName);
sql.append(" = ?");
return sql.toString();
}
public static String buildDeleteSql(String tableName,String idName){
StringBuilder sql = new StringBuilder();
sql.append("delete ");
sql.append(" from ");
sql.append(tableName);
sql.append(" where ");
sql.append(idName);
sql.append(" = ?");
return sql.toString();
}
}