List of usage examples for java.sql ResultSetMetaData getColumnDisplaySize
int getColumnDisplaySize(int column) throws SQLException;
From source file:SeeAccount.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;//from w w w . ja va 2s .co m Connection connection = null; Statement statement = null; ResultSet rs; try { outResponse.setContentType("text/html"); out = outResponse.getWriter(); Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM acc_acc"); ResultSetMetaData md = rs.getMetaData(); out.println("<HTML><HEAD><TITLE> Thumbnail Identification Record</TITLE></HEAD>"); out.println("<BODY>"); out.println("Account Information:<BR>"); out.println("<table>"); out.println("<tr><td>"); for (int i = 1; i <= md.getColumnCount(); i++) { out.println("Column #" + i + "<BR>"); out.println("getColumnName : " + md.getColumnName(i) + "<BR>"); out.println("getColumnClassName : " + md.getColumnClassName(i) + "<BR>"); out.println("getColumnDisplaySize : " + md.getColumnDisplaySize(i) + "<BR>"); out.println("getColumnType : " + md.getColumnType(i) + "<BR>"); out.println("getTableName : " + md.getTableName(i) + "<BR>"); out.println("<HR>"); } out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }
From source file:kenh.xscript.database.beans.ResultSetBean.java
/** * Use result set to initial a bean.//from w w w.ja v a 2s.c o m * * @param rs * @param includeFieldName * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public ResultSetBean(ResultSet rs, boolean includeFieldName) throws SQLException, IllegalAccessException, InstantiationException { include_field_name = includeFieldName; LazyDynaClass beanClass = new LazyDynaClass(); ResultSetMetaData m = rs.getMetaData(); for (int i = 1; i <= m.getColumnCount(); i++) { Column c = new Column(); try { c.catalogName = m.getCatalogName(i); } catch (SQLException e) { } try { c.className = m.getColumnClassName(i); } catch (SQLException e) { } try { c.displaySize = m.getColumnDisplaySize(i); } catch (SQLException e) { } try { c.label = m.getColumnLabel(i); } catch (SQLException e) { } try { c.name = m.getColumnName(i); } catch (SQLException e) { } try { c.type = m.getColumnType(i); } catch (SQLException e) { } try { c.typeName = m.getColumnTypeName(i); } catch (SQLException e) { } try { c.precision = m.getPrecision(i); } catch (SQLException e) { } try { c.scale = m.getScale(i); } catch (SQLException e) { } try { c.schemaName = m.getSchemaName(i); } catch (SQLException e) { } try { c.tableName = m.getTableName(i); } catch (SQLException e) { } beanClass.add(m.getColumnLabel(i).toLowerCase()); beanClass.add("" + i); cols.add(c); } DynaBean colBean = beanClass.newInstance(); int i = 1; for (Column col : cols) { String field = col.getLabel().toLowerCase(); colBean.set(field, col.getLabel()); colBean.set("" + i, col.getLabel()); i++; } if (include_field_name) rows.add(colBean); while (rs.next()) { DynaBean bean = beanClass.newInstance(); i = 1; for (Column c : cols) { String field = c.getLabel().toLowerCase(); Object obj = rs.getObject(field); bean.set(field, obj); bean.set("" + i, obj); i++; } rows.add(bean); } }
From source file:org.apache.kylin.query.adhoc.PushDownRunnerJdbcImpl.java
@Override public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws Exception { Statement statement = null;// w w w . j a v a 2 s. c om Connection connection = this.getConnection(); ResultSet resultSet = null; //extract column metadata ResultSetMetaData metaData = null; int columnCount = 0; try { statement = connection.createStatement(); resultSet = statement.executeQuery(query); extractResults(resultSet, results); metaData = resultSet.getMetaData(); 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)); } } catch (SQLException sqlException) { throw sqlException; } finally { DBUtils.closeQuietly(resultSet); DBUtils.closeQuietly(statement); closeConnection(connection); } }
From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java
private void columnDefinition(final int idx, final ResultSetMetaData context) throws XMLStreamException, SQLException { // @formatter:off xml.writeStartElement(WRS, "column-definition"); tag("column-index", idx); tag("auto-increment", context.isAutoIncrement(idx)); tag("case-sensitive", context.isCaseSensitive(idx)); tag("currency", context.isCurrency(idx)); tag("nullable", context.isNullable(idx)); tag("signed", context.isSigned(idx)); tag("searchable", context.isSearchable(idx)); tag("column-display-size", context.getColumnDisplaySize(idx)); tag("column-label", context.getColumnLabel(idx)); tag("column-name", context.getColumnName(idx)); tag("schema-name", context.getSchemaName(idx)); tag("column-precision", context.getPrecision(idx)); tag("column-scale", context.getScale(idx)); tag("table-name", context.getTableName(idx)); tag("catalog-name", context.getCatalogName(idx)); tag("column-type", context.getColumnType(idx)); tag("column-type-name", context.getColumnTypeName(idx)); xml.writeEndElement();/*from ww w .jav a2s . c o m*/ // @formatter:on }
From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java
/** * Constructs a new ColumnMetaData objects from given ResultSetMetaData with provided column default values map and * the object's index.// ww w .j av a 2 s . co m * * @param rsmd * A ResultSetMetaData which contains meta information about all columns for the table. * @param columnDefaultValues * A map of possibly defined values by default for columns. * @param i * Index of column which should be constructed. * @return A constructed ColumnMetaData object. * @throws SQLException * Is thrown in case any errors during work with database occur. */ private ColumnMetaData getColumnMetaData(ResultSetMetaData rsmd, Map<String, String> columnDefaultValues, int i) throws SQLException { SqlTypes columnType = SqlTypes.getSqlTypeByJdbcSqlType(rsmd.getColumnType(i)); ColumnMetaData column = ColumnMetaData.getInstance(rsmd.getColumnName(i), columnType) .setNullable(rsmd.isNullable(i) == ResultSetMetaData.columnNullable) .setAutoincrement(rsmd.isAutoIncrement(i)); if (columnDefaultValues.containsKey(rsmd.getColumnName(i))) { column.setDefaultValue(columnDefaultValues.get(rsmd.getColumnName(i))); } if (columnType.isHasSize()) { column.setSize(rsmd.getColumnDisplaySize(i)); } return column; }
From source file:kr.co.bitnine.octopus.engine.CursorHive.java
@Override public TupleDesc describe() throws PostgresException { if (tupDesc != null) return tupDesc; prepareConnection();//from w w w .ja v a2 s . com prepareStatement(0); try { checkCancel(); ResultSet rs = stmt.executeQuery(); checkCancel(); ResultSetMetaData rsmd = rs.getMetaData(); int colCnt = rsmd.getColumnCount(); PostgresAttribute[] attrs = new PostgresAttribute[colCnt]; for (int i = 0; i < colCnt; i++) { String colName = getColumnName(rsmd.getColumnName(i + 1)); int colType = rsmd.getColumnType(i + 1); LOG.debug("JDBC type of column '" + colName + "' is " + colType); PostgresType type = TypeInfo.postresTypeOfJdbcType(colType); int typeInfo = -1; if (type == PostgresType.VARCHAR) typeInfo = rsmd.getColumnDisplaySize(i + 1); attrs[i] = new PostgresAttribute(colName, type, typeInfo); } rs.close(); stmt.close(); stmt = null; tupDesc = new TupleDesc(attrs, getResultFormats()); return tupDesc; } catch (SQLException e) { PostgresErrorData edata = new PostgresErrorData(PostgresSeverity.ERROR, "failed to execute by-pass query: " + e.getMessage()); throw new PostgresException(edata, e); } }
From source file:kr.co.bitnine.octopus.engine.CursorByPass.java
private void execute(int numRows) throws PostgresException { if (getState() == State.DONE || getState() == State.FAILED) setState(State.READY);/* w w w .j a v a 2 s. c o m*/ if (getState() != State.READY) return; LOG.debug("execute CursorByPass (rows=" + numRows + ")"); try { // NOTE: some JDBC drivers do not ignore setFetchSize(0) if (numRows > 0) stmt.setFetchSize(numRows); checkCancel(); ResultSet rs = stmt.executeQuery(); checkCancel(); ResultSetMetaData rsmd = rs.getMetaData(); int colCnt = rsmd.getColumnCount(); PostgresAttribute[] attrs = new PostgresAttribute[colCnt]; for (int i = 0; i < colCnt; i++) { String colName = rsmd.getColumnName(i + 1); int colType = rsmd.getColumnType(i + 1); LOG.info("JDBC type of column '" + colName + "' is " + colType); PostgresType type = TypeInfo.postresTypeOfJdbcType(colType); int typeInfo = -1; if (type == PostgresType.VARCHAR) typeInfo = rsmd.getColumnDisplaySize(i + 1); attrs[i] = new PostgresAttribute(colName, type, typeInfo); } tupDesc = new TupleDesc(attrs, getResultFormats()); tupSetByPass = new TupleSetByPass(this, rs, tupDesc); setState(State.ACTIVE); } catch (SQLException e) { setState(State.FAILED); close(); PostgresErrorData edata = new PostgresErrorData(PostgresSeverity.ERROR, "failed to execute by-pass query: " + e.getMessage()); throw new PostgresException(edata, e); } }
From source file:com.kylinolap.rest.service.QueryService.java
/** * @param sql//from w w w. ja va2 s. c o m * @param project * @return * @throws Exception */ private SQLResponse execute(String sql, SQLRequest sqlRequest) throws Exception { Connection conn = null; Statement stat = null; ResultSet resultSet = null; List<List<String>> results = new LinkedList<List<String>>(); List<SelectedColumnMeta> columnMetas = new LinkedList<SelectedColumnMeta>(); try { conn = getOLAPDataSource(sqlRequest.getProject()).getConnection(); if (sqlRequest instanceof PrepareSqlRequest) { PreparedStatement preparedState = conn.prepareStatement(sql); for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) { setParam(preparedState, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]); } resultSet = preparedState.executeQuery(); } else { stat = conn.createStatement(); resultSet = stat.executeQuery(sql); } ResultSetMetaData metaData = resultSet.getMetaData(); int 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), metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i), metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i))); } List<String> oneRow = new LinkedList<String>(); // fill in results while (resultSet.next()) { for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(new LinkedList<String>(oneRow)); oneRow.clear(); } } catch (Exception e) { logger.error(e.getLocalizedMessage(), e); throw e; } finally { close(resultSet, stat, conn); } boolean isPartialResult = false; String cube = ""; long totalScanCount = 0; for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { isPartialResult |= ctx.storageContext.isPartialResultReturned(); cube = ctx.cubeInstance.getName(); totalScanCount += ctx.storageContext.getTotalScanCount(); } SQLResponse response = new SQLResponse(columnMetas, results, cube, 0, false, null, isPartialResult); response.setTotalScanCount(totalScanCount); return response; }
From source file:org.apache.bigtop.itest.hive.TestJdbc.java
@Test public void preparedStmtAndResultSet() throws SQLException { final String tableName = "bigtop_jdbc_psars_test_table"; try (Statement stmt = conn.createStatement()) { stmt.execute("drop table if exists " + tableName); stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, " + "i int, lo bigint, sh smallint, st varchar(32))"); }// w w w . j a va2 s. c o m // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I // try to put them in the query. try (PreparedStatement ps = conn .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) { ps.setBoolean(1, true); ps.setByte(2, (byte) 1); ps.setDouble(3, 3.141592654); ps.setFloat(4, 3.14f); ps.setInt(5, 3); ps.setLong(6, 10L); ps.setShort(7, (short) 20); ps.setString(8, "abc"); ps.executeUpdate(); } try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ps.setNull(1, Types.INTEGER); ps.setObject(2, "mary had a little lamb"); ps.executeUpdate(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.clearParameters(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.execute(); } try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from " + tableName); ResultSetMetaData md = rs.getMetaData(); int colCnt = md.getColumnCount(); LOG.debug("Column count is " + colCnt); for (int i = 1; i <= colCnt; i++) { LOG.debug("Looking at column " + i); String strrc = md.getColumnClassName(i); LOG.debug("Column class name is " + strrc); int intrc = md.getColumnDisplaySize(i); LOG.debug("Column display size is " + intrc); strrc = md.getColumnLabel(i); LOG.debug("Column label is " + strrc); strrc = md.getColumnName(i); LOG.debug("Column name is " + strrc); intrc = md.getColumnType(i); LOG.debug("Column type is " + intrc); strrc = md.getColumnTypeName(i); LOG.debug("Column type name is " + strrc); intrc = md.getPrecision(i); LOG.debug("Precision is " + intrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); boolean boolrc = md.isAutoIncrement(i); LOG.debug("Is auto increment? " + boolrc); boolrc = md.isCaseSensitive(i); LOG.debug("Is case sensitive? " + boolrc); boolrc = md.isCurrency(i); LOG.debug("Is currency? " + boolrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); intrc = md.isNullable(i); LOG.debug("Is nullable? " + intrc); boolrc = md.isReadOnly(i); LOG.debug("Is read only? " + boolrc); } while (rs.next()) { LOG.debug("bo = " + rs.getBoolean(1)); LOG.debug("bo = " + rs.getBoolean("bo")); LOG.debug("ti = " + rs.getByte(2)); LOG.debug("ti = " + rs.getByte("ti")); LOG.debug("db = " + rs.getDouble(3)); LOG.debug("db = " + rs.getDouble("db")); LOG.debug("fl = " + rs.getFloat(4)); LOG.debug("fl = " + rs.getFloat("fl")); LOG.debug("i = " + rs.getInt(5)); LOG.debug("i = " + rs.getInt("i")); LOG.debug("lo = " + rs.getLong(6)); LOG.debug("lo = " + rs.getLong("lo")); LOG.debug("sh = " + rs.getShort(7)); LOG.debug("sh = " + rs.getShort("sh")); LOG.debug("st = " + rs.getString(8)); LOG.debug("st = " + rs.getString("st")); LOG.debug("tm = " + rs.getObject(8)); LOG.debug("tm = " + rs.getObject("st")); LOG.debug("tm was null " + rs.wasNull()); } LOG.debug("bo is column " + rs.findColumn("bo")); int intrc = rs.getConcurrency(); LOG.debug("concurrency " + intrc); intrc = rs.getFetchDirection(); LOG.debug("fetch direction " + intrc); intrc = rs.getType(); LOG.debug("type " + intrc); Statement copy = rs.getStatement(); SQLWarning warning = rs.getWarnings(); while (warning != null) { LOG.debug("Found a warning: " + warning.getMessage()); warning = warning.getNextWarning(); } rs.clearWarnings(); } }
From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java
public List<DBColumn> getColumns(String schema, String table) throws NextSqlException, MalformedTableNameException { Connection con;// w w w . jav a 2 s.c o m List<DBColumn> columns = new ArrayList<DBColumn>(); String schemaName; String escapedTableName; try { con = Globals.getConnection(); if (schema == null) { schemaName = Globals.getConnection().getMetaData().getUserName(); } else { schemaName = schema; } Dialect dialect = Globals.getDialect(); if (dialect.isKeyWord(table)) { escapedTableName = dialect.getEscapedKeyWord(table); } else { escapedTableName = table; } } catch (Exception e) { throw new NextSqlException("Could not retrieve connection.", e); } ResultSet rs = null; Statement stmt = null; List<String> keyColumns = new ArrayList<String>(); try { // primary keys DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getPrimaryKeys(null, schemaName, table); while (rs.next()) { keyColumns.add(rs.getString("COLUMN_NAME")); } closeResultSet(rs); // foreign keys rs = dbmd.getImportedKeys(null, schemaName, table); List<String> foreignColumns = new ArrayList<String>(); HashMap<String, DBForeignColumnInfo> fkMap = new HashMap<String, DBForeignColumnInfo>(); while (rs.next()) { String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String fkColumn = rs.getString("FKCOLUMN_NAME"); String pkSchema = rs.getString("PKTABLE_SCHEM"); String pkTable = rs.getString("PKTABLE_NAME"); String pkColumn = rs.getString("PKCOLUMN_NAME"); DBForeignColumnInfo fkInfo = new DBForeignColumnInfo(fkSchema, fkTable, fkColumn, pkSchema, pkTable, pkColumn); //System.out.println("fkInfo : " + fkInfo); foreignColumns.add(fkColumn); fkMap.put(fkColumn, fkInfo); } closeResultSet(rs); // column names with index rs = dbmd.getIndexInfo(null, schemaName, table, false, true); List<String> indexes = new ArrayList<String>(); while (rs.next()) { String indexName = rs.getString(9); if (indexName != null) { indexes.add(indexName); } } closeResultSet(rs); DataSource ds = DefaultDataSourceManager.getInstance().getConnectedDataSource(); String header = ""; stmt = con.createStatement(); try { // workaround if a table name contains spaces if (escapedTableName.indexOf(" ") != -1) { escapedTableName = "\"" + escapedTableName + "\""; } String prefix = ""; if (!NO_SCHEMA_NAME.equals(schemaName)) { prefix = schemaName; } if (prefix.indexOf(" ") != -1) { prefix = "\"" + prefix + "\""; } if (!"".equals(prefix)) { prefix = prefix + "."; } if (ds.getDriver().equals(CSVDialect.DRIVER_CLASS)) { header = (String) ds.getProperties().get("headerline"); if (header == null) { header = ""; } } if (header.isEmpty()) { String s = "SELECT * FROM " + prefix + escapedTableName + " WHERE 1 = 0"; LOG.info("getColumns[ " + s + "]"); rs = stmt.executeQuery(s); } } catch (SQLException e) { e.printStackTrace(); throw new MalformedTableNameException(e); } if (header.isEmpty()) { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int col = 1; col <= columnCount; col++) { String name = rsmd.getColumnLabel(col); int length = rsmd.getColumnDisplaySize(col); int precision = rsmd.getPrecision(col); int scale = rsmd.getScale(col); boolean isPrimaryKey = false; boolean isForeignKey = false; boolean isIndex = false; if (keyColumns.contains(name)) { isPrimaryKey = true; } DBForeignColumnInfo fkInfo = null; if (foreignColumns.contains(name)) { isForeignKey = true; fkInfo = fkMap.get(name); } if (indexes.contains(name)) { isIndex = true; } DBColumn column = new DBColumn(schemaName, table, name, rsmd.getColumnTypeName(col), isPrimaryKey, isForeignKey, isIndex, fkInfo, length, precision, scale); columns.add(column); } } else { String columnTypes = (String) ds.getProperties().get("columnTypes"); String[] names = header.split(","); String[] types = new String[names.length]; for (int i = 0; i < types.length; i++) { types[i] = "String"; } if ((columnTypes != null) && !columnTypes.isEmpty()) { types = columnTypes.split(","); } for (int i = 0; i < names.length; i++) { DBColumn column = new DBColumn(schemaName, table, names[i], types[i], false, false, false, null, 20, 0, 0); columns.add(column); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(rs); closeStatement(stmt); } return columns; }