线上数据 导 线下数据时 需要,导出insert 的 sql 语句
解析resultset 中的 元数据 metadata ,获取结果集的 column名及对应的columnvalue,拼接成sql
@Override
public MetaData mapRow(ResultSet rs, int rowNum) throws SQLException {
MetaData data = new MetaData();
StringBuilder sb = new StringBuilder();
ResultSetMetaData metaData = rs.getMetaData();
String tableName = metaData.getTableName(1);
sb.append("INSERT INTO ").append(tableName);
Map<String,String> pair = getColumnsPair(rs);
StringBuffer firstSb = new StringBuffer();
StringBuffer lastSb = new StringBuffer();
for(Map.Entry<String,String> entry : pair.entrySet()){
firstSb.append(entry.getKey()).append(",");
lastSb.append(entry.getValue()).append(",");
}
firstSb.deleteCharAt(firstSb.length() - 1);
lastSb.deleteCharAt(lastSb.length() - 1);
sb.append(" ( ").append(firstSb).append(" ) VALUES ( ").append(lastSb).append(" );\n");
data.setID(rs.getInt("ID"));
data.setSql(sb.toString());
return data;
}
private Map<String,String> getColumnsPair(ResultSet rs) throws SQLException {
Map<String,String> result = Maps.newHashMap();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for(int i=1;i<=columnCount;i++){
result.put(metaData.getColumnName(i),
getColumnValue(metaData.getColumnName(i),metaData.getColumnType(i),i,rs));
}
return result;
}
private String getColumnValue(String columnName,int columnType,int i,ResultSet rs) throws SQLException {
switch(columnType){
case Types.NUMERIC :return rs.getLong(i) + "";
case Types.VARCHAR:
return (rs.getString(i) == null) ? null : "'"+rs.getString(i)+"'";
case Types.DATE:
return (rs.getDate(i) == null) ? null:"'"+DateUtil.dateToString(rs.getDate(i), "yyyy-MM-dd")+"'";
case Types.TIMESTAMP:
return (rs.getTimestamp(i) == null) ? null:"'"+DateUtil.dateToString(rs.getTimestamp(i),"yyyy-MM-dd HH:mm:ss")+"'";
//case Types.TIME:return rs.getTime(i);
case Types.BOOLEAN:return rs.getInt(i) + "";
//case Types.ARRAY :return rs.getArray(i);
case Types.BIGINT :return rs.getLong(i) + "";
//case Types.BINARY:return rs.getBinaryStream(i);
//case Types.BLOB:return rs.getBlob(i);
case Types.CHAR:
return (rs.getString(i) == null) ? null : "'"+rs.getString(i)+"'";
case Types.INTEGER:return rs.getInt(i) + "";
case Types.DOUBLE :return rs.getDouble(i) + "";
case Types.FLOAT:return rs.getFloat(i) + "";
case Types.SMALLINT:return rs.getInt(i) + "";
case Types.TINYINT:return rs.getInt(i) + "";
case Types.DECIMAL:return rs.getLong(i) + "";
default:return null;
}
}