List of usage examples for java.sql ResultSetMetaData getColumnTypeName
String getColumnTypeName(int column) throws SQLException;
From source file:oscar.form.FrmRecordHelp.java
public ResultSet updateResultSet(Properties props, ResultSet rs, boolean bInsert) throws SQLException { ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { String name = md.getColumnName(i); if (name.equalsIgnoreCase("ID")) { if (bInsert) rs.updateInt(name, 0);//from ww w .j a v a 2 s .c om continue; } String value = props.getProperty(name, null); if (md.getColumnTypeName(i).startsWith("TINY")) { if (value != null) { if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("checked='checked'")) { rs.updateInt(name, 1); } else { rs.updateInt(name, 0); } } else { rs.updateInt(name, 0); } continue; } if (md.getColumnTypeName(i).equalsIgnoreCase("date")) { java.util.Date d; if (md.getColumnName(i).equalsIgnoreCase("formEdited")) { d = UtilDateUtilities.Today(); } else { if ((value == null) || (value.indexOf('/') != -1)) d = UtilDateUtilities.StringToDate(value, _dateFormat); else d = UtilDateUtilities.StringToDate(value, _newDateFormat); } if (d == null) rs.updateNull(name); else rs.updateDate(name, new java.sql.Date(d.getTime())); continue; } if (md.getColumnTypeName(i).equalsIgnoreCase("timestamp")) { Date d; if (md.getColumnName(i).equalsIgnoreCase("formEdited")) { d = UtilDateUtilities.Today(); } else { d = UtilDateUtilities.StringToDate(value, "yyyyMMddHHmmss"); } if (d == null) rs.updateNull(name); else rs.updateTimestamp(name, new java.sql.Timestamp(d.getTime())); continue; } if (value == null) rs.updateNull(name); else rs.updateString(name, value); } return rs; }
From source file:com.mvdb.etl.dao.impl.JdbcOrderDAO.java
@Override public Map<String, ColumnMetadata> findMetadata() { String sql = "SELECT * FROM ORDERS limit 1"; final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>(); getJdbcTemplate().query(sql, new RowCallbackHandler() { @Override/*from w ww . j av a2 s .c o m*/ public void processRow(ResultSet row) throws SQLException { ResultSetMetaData rsm = row.getMetaData(); int columnCount = rsm.getColumnCount(); for (int column = 1; column < (columnCount + 1); column++) { ColumnMetadata metadata = new ColumnMetadata(); metadata.setColumnLabel(rsm.getColumnLabel(column)); metadata.setColumnName(rsm.getColumnName(column)); metadata.setColumnType(rsm.getColumnType(column)); metadata.setColumnTypeName(rsm.getColumnTypeName(column)); metaDataMap.put(rsm.getColumnName(column), metadata); } } }); return metaDataMap; }
From source file:org.rhq.plugins.postgres.PostgresDatabaseComponent.java
public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, Exception { if ("resetStatistics".equals(name)) { Statement stmt = null;//from w w w.j a v a 2s . c o m ResultSet rs = null; try { stmt = getConnection().createStatement(); rs = stmt.executeQuery("select * from pg_stat_reset()"); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } return null; } else if ("invokeSql".equals(name)) { Statement stmt = null; ResultSet rs = null; try { stmt = getConnection().createStatement(); String sql = parameters.getSimple("sql").getStringValue(); OperationResult result = new OperationResult(); if (parameters.getSimple("type").getStringValue().equals("update")) { int updateCount = stmt.executeUpdate(sql); result.getComplexResults() .put(new PropertySimple("result", "Query updated " + updateCount + " rows")); } else { rs = stmt.executeQuery(parameters.getSimple("sql").getStringValue()); ResultSetMetaData md = rs.getMetaData(); StringBuilder buf = new StringBuilder(); int rowCount = 0; buf.append("<table>"); buf.append("<th>"); for (int i = 1; i <= md.getColumnCount(); i++) { buf.append("<td>"); buf.append(md.getColumnName(i) + " (" + md.getColumnTypeName(i) + ")"); buf.append("</td>"); } buf.append("</th>"); while (rs.next()) { rowCount++; buf.append("<tr>"); for (int i = 1; i <= md.getColumnCount(); i++) { buf.append("<td>"); buf.append(rs.getString(i)); buf.append("</td>"); } buf.append("</tr>"); } buf.append("</table>"); result.getComplexResults() .put(new PropertySimple("result", "Query returned " + rowCount + " rows")); result.getComplexResults().put(new PropertySimple("contents", buf.toString())); } return result; } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } } else { throw new UnsupportedOperationException("Operation [" + name + "] is not supported yet."); } }
From source file:org.xsystem.sql2.dml.DmlCommand.java
Map<String, Object> rowAsMap(ResultSet rs) throws SQLException { Map row = new LinkedHashMap(); Connection con = rs.getStatement().getConnection(); AbstactNativeHelper nativeHelper = nativeHelperFactory(con); ResultSetMetaData metaData = rs.getMetaData(); int cnt = metaData.getColumnCount(); for (int i = 1; i <= cnt; i++) { String cn = metaData.getColumnName(i); int jdbcType = metaData.getColumnType(i); String colTypeName = metaData.getColumnTypeName(i); Object value = rs.getObject(i); if (rs.wasNull()) { value = null;/*from w ww . j av a 2s. com*/ } if (upperTag != null) { if (upperTag) { cn = cn.toUpperCase(); } else { cn = cn.toLowerCase(); } } value = getValue(value, jdbcType, colTypeName, con, nativeHelper); row.put(cn, value); } return row; }
From source file:ro.nextreports.engine.util.QueryUtil.java
public List<NameType> executeQueryForColumnNames(String sql) throws Exception { // long t = System.currentTimeMillis(); StringWriter sw = new StringWriter(100); // sw.append("SELECT * FROM ("); sw.append(sql);//www .j av a 2 s . c o m // sw.append(") A WHERE 1 = -1"); String sqlForHeader = sw.toString(); LOG.info("call for header columns = " + sqlForHeader); ResultSet rs = null; Statement stmt = null; try { if (isProcedureCall(sqlForHeader)) { Dialect dialect = DialectUtil.getDialect(con); CallableStatement cs = con.prepareCall("{" + sqlForHeader + "}"); stmt = cs; if (dialect.hasProcedureWithCursor()) { cs.registerOutParameter(1, dialect.getCursorSqlType()); } rs = cs.executeQuery(); if (dialect.hasProcedureWithCursor()) { rs = (ResultSet) (cs.getObject(1)); } } else { stmt = con.createStatement(); stmt.setMaxRows(1); rs = stmt.executeQuery(sqlForHeader); } ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); List<NameType> columnNames = new ArrayList<NameType>(); for (int i = 0; i < columnCount; i++) { columnNames.add(new NameType(rsmd.getColumnLabel(i + 1), dialect.getJavaType( rsmd.getColumnTypeName(i + 1), rsmd.getPrecision(i + 1), rsmd.getScale(i + 1)))); // rsmd.getColumnClassName(i + 1))); } // t = System.currentTimeMillis() - t; // System.out.println("execute query for column names in " + t + // "ms"); return columnNames; } finally { ConnectionUtil.closeResultSet(rs); ConnectionUtil.closeStatement(stmt); } }
From source file:org.apache.calcite.test.CalciteAssert.java
private static String typeString(ResultSetMetaData metaData) throws SQLException { final List<String> list = new ArrayList<>(); for (int i = 0; i < metaData.getColumnCount(); i++) { list.add(metaData.getColumnName(i + 1) + " " + metaData.getColumnTypeName(i + 1) + (metaData.isNullable(i + 1) == ResultSetMetaData.columnNoNulls ? " NOT NULL" : "")); }//from w ww . j av a2s .c om return list.toString(); }
From source file:org.orbisgis.orbisserver.baseserver.model.Session.java
/** * Returns the DatabaseContent object which contains the representation of the Database. * @return The DatabaseContent object.// w w w .j a v a 2 s. co m */ public DatabaseContent getDatabaseContent() { DatabaseContent dbContent = new DatabaseContent(); try (Connection connection = ds.getConnection()) { for (String tableName : JDBCUtilities.getTableNames(connection.getMetaData(), null, null, null, new String[] { "TABLE", "LINKED TABLE", "VIEW", "EXTERNAL", "UIodfsghjmodfhjgodujhfg" })) { DatabaseTable dbTable = new DatabaseTable(TableLocation.parse(tableName)); //Get the list of the columns of a table ResultSet rs1 = connection.createStatement() .executeQuery(String.format("select * from %s limit 1", dbTable.getName())); ResultSetMetaData metaData = rs1.getMetaData(); //If the column isn't a geometry, add it to the map for (int i = 1; i <= metaData.getColumnCount(); i++) { if (!metaData.getColumnTypeName(i).equalsIgnoreCase("GEOMETRY")) { dbTable.addField(metaData.getColumnLabel(i), metaData.getColumnTypeName(i)); } } //Once the non geometric columns are get, do the same with the geometric one. Statement statement = connection.createStatement(); String query = String.format("SELECT * FROM GEOMETRY_COLUMNS WHERE F_TABLE_NAME LIKE '%s';", TableLocation.parse(dbTable.getName()).getTable()); ResultSet rs = statement.executeQuery(query); while (rs.next()) { dbTable.addField(rs.getString(4), SFSUtilities.getGeometryTypeNameFromCode(rs.getInt(6))); } dbContent.addTable(dbTable); } } catch (SQLException e) { LOGGER.error("Unable to get the database information.\nCause : " + e.getMessage()); } return dbContent; }
From source file:org.voltdb.HsqlBackend.java
public VoltTable runDML(String dml) { dml = dml.trim();/*from www .j a v a 2 s . c o m*/ String indicator = dml.substring(0, 1).toLowerCase(); if (indicator.equals("s") || // "s" is for "select ..." indicator.equals("(")) { // "(" is for "(select ... UNION ...)" et. al. try { Statement stmt = dbconn.createStatement(); sqlLog.l7dlog(Level.DEBUG, LogKeys.sql_Backend_ExecutingDML.name(), new Object[] { dml }, null); sqlLog.debug("Executing " + dml); ResultSet rs = stmt.executeQuery(dml); ResultSetMetaData rsmd = rs.getMetaData(); // note the index values here carefully VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[rsmd.getColumnCount()]; for (int i = 1; i <= rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnLabel(i); String type = rsmd.getColumnTypeName(i); //LOG.fine("Column type: " + type); if (type.equals("VARCHAR")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING); else if (type.equals("TINYINT")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TINYINT); else if (type.equals("SMALLINT")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.SMALLINT); else if (type.equals("INTEGER")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.INTEGER); else if (type.equals("BIGINT")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.BIGINT); else if (type.equals("DECIMAL")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.DECIMAL); else if (type.equals("FLOAT")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.FLOAT); else if (type.equals("TIMESTAMP")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TIMESTAMP); else if (type.equals("VARBINARY")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.VARBINARY); else if (type.equals("CHARACTER")) columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING); else throw new ExpectedProcedureException( "Trying to create a column in Backend with a (currently) unsupported type: " + type); } VoltTable table = new VoltTable(columns); while (rs.next()) { Object[] row = new Object[table.getColumnCount()]; for (int i = 0; i < table.getColumnCount(); i++) { if (table.getColumnType(i) == VoltType.STRING) row[i] = rs.getString(i + 1); else if (table.getColumnType(i) == VoltType.TINYINT) row[i] = rs.getByte(i + 1); else if (table.getColumnType(i) == VoltType.SMALLINT) row[i] = rs.getShort(i + 1); else if (table.getColumnType(i) == VoltType.INTEGER) row[i] = rs.getInt(i + 1); else if (table.getColumnType(i) == VoltType.BIGINT) row[i] = rs.getLong(i + 1); else if (table.getColumnType(i) == VoltType.DECIMAL) row[i] = rs.getBigDecimal(i + 1); else if (table.getColumnType(i) == VoltType.FLOAT) row[i] = rs.getDouble(i + 1); else if (table.getColumnType(i) == VoltType.VARBINARY) row[i] = rs.getBytes(i + 1); else if (table.getColumnType(i) == VoltType.TIMESTAMP) { Timestamp t = rs.getTimestamp(i + 1); if (t == null) { row[i] = null; } else { // convert from millisecond to microsecond granularity row[i] = new org.voltdb.types.TimestampType(t.getTime() * 1000); } } else { throw new ExpectedProcedureException( "Trying to read a (currently) unsupported type from a JDBC resultset."); } if (rs.wasNull()) { // JDBC returns 0/0.0 instead of null. Put null into the row. row[i] = null; } } table.addRow(row); } stmt.close(); rs.close(); return table; } catch (Exception e) { if (e instanceof ExpectedProcedureException) { throw (ExpectedProcedureException) e; } sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e); throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e); } } else { try { Statement stmt = dbconn.createStatement(); sqlLog.debug("Executing: " + dml); long ucount = stmt.executeUpdate(dml); sqlLog.debug(" result: " + String.valueOf(ucount)); VoltTable table = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); table.addRow(ucount); return table; } catch (SQLException e) { // glorious hack to determine if the error is a constraint failure if (e.getMessage().contains("constraint")) { sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_ConvertingHSQLExtoCFEx.name(), e); final byte messageBytes[] = e.getMessage().getBytes(); ByteBuffer b = ByteBuffer.allocate(25 + messageBytes.length); b.putInt(messageBytes.length); b.put(messageBytes); b.put(e.getSQLState().getBytes()); b.putInt(0); // ConstraintFailure.type try { FastSerializer.writeString("HSQL", b); } catch (IOException e1) { e1.printStackTrace(); } b.putInt(0);//Table size is 0 b.rewind(); throw new ConstraintFailureException(b); } else { sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e); throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e); } } catch (Exception e) { // rethrow an expected exception sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e); throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e); } } }
From source file:org.apache.kylin.rest.util.HiveReroute.java
private void extractColumnMetadata(ResultSet resultSet, List<SelectedColumnMeta> columnMetas) throws SQLException { ResultSetMetaData metaData = null; int columnCount = 0; metaData = resultSet.getMetaData();//from w w w . j a v a2 s .co m columnCount = metaData.getColumnCount(); // fill in selected column meta for (int i = 1; i <= columnCount; ++i) { columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i), false, metaData.isCurrency(i), metaData.isNullable(i), false, metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false)); } }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testPreparedStatementMetaData() throws SQLException { PreparedStatement prep = conn.prepareStatement("select * from table(x int = ?, name varchar = ?)"); ResultSetMetaData meta = prep.getMetaData(); assertEquals(2, meta.getColumnCount()); assertEquals("INTEGER", meta.getColumnTypeName(1)); assertEquals("VARCHAR", meta.getColumnTypeName(2)); prep = conn.prepareStatement("call 1"); meta = prep.getMetaData();/*from ww w. j a va 2s . com*/ assertEquals(1, meta.getColumnCount()); assertEquals("INTEGER", meta.getColumnTypeName(1)); }