JDBC-根据ResultSet返回值生成Insert-Sql语句
Posted OkidoGreen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC-根据ResultSet返回值生成Insert-Sql语句相关的知识,希望对你有一定的参考价值。
线上数据 导 线下数据时 需要,导出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;
以上是关于JDBC-根据ResultSet返回值生成Insert-Sql语句的主要内容,如果未能解决你的问题,请参考以下文章
jdbc数据库连接在方法中,而且要返回statement 或resultset 在方法里关闭连接会怎么样?要怎么处理?
ResultSet 不为空,但 resultset.next() 返回 false