0
点赞
收藏
分享

微信扫一扫

查询表字段类型

灵魂跑者 2022-08-17 阅读 74

/*

* 根据表明查询字段类型

* */

private Map<String, Integer> queryFieldMap(String tableName, String dbName){

if(tableName == null || dbName == null){

return null;

}


Map<String, Integer> resultMap = new HashMap<String, Integer>();


Connection conn = null;

Statement stat = null;

ResultSet rs = null;



try {

conn = ConnectionPool.getInstance().getConnection(dbName);

stat = conn.createStatement();

rs = stat.executeQuery("select * from " + tableName + " where 1 = 0");

ResultSetMetaData rsmd = rs.getMetaData();

int count = rsmd.getColumnCount();

for(int index = 1; index <= count; index++){

String colName = rsmd.getColumnName(index).toLowerCase();

int colType = rsmd.getColumnType(index);


resultMap.put(colName, colType);

}

} catch (SQLException e) {

log.error(e.getMessage());

e.printStackTrace();

resultMap = null;

} finally {

try { rs.close(); } catch (Exception e) { e.printStackTrace(); }

try { stat.close(); } catch (Exception e) { e.printStackTrace(); }

try { conn.close(); } catch (Exception e) { e.printStackTrace(); }

}


return resultMap;
}
2.引用的地方:
fieldType = fieldTypeMap.get(fieldName.toLowerCase());

if(fieldType == java.sql.Types.VARCHAR){ //String
PreStatSetValue.setString(pstmt, index + 1, fieldValue);
} else if(fieldType == java.sql.Types.INTEGER || fieldType == java.sql.Types.NUMERIC || fieldType == java.sql.Types.SMALLINT){ //int
try{
PreStatSetValue.setInt(pstmt, index + 1, Integer.parseInt(fieldValue));
}catch(Exception e){
log.error("更新cssf_ts_statistics, 字段值设置错误:fieldName = " + fieldName + ", 要求类型:" + fieldType + ", 设置值:" + fieldValue);
PreStatSetValue.setInt(pstmt, index + 1, 0);
}

} else if(fieldType == java.sql.Types.DATE || fieldType == java.sql.Types.TIMESTAMP){ //date
PreStatSetValue.setTimestamp(pstmt, index + 1, fieldValue);
}

举报

相关推荐

0 条评论