List of usage examples for java.sql ResultSetMetaData columnNoNulls
int columnNoNulls
To view the source code for java.sql ResultSetMetaData columnNoNulls.
Click Source Link
NULL
values. From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName(DRIVER);//from ww w .j av a 2s . c o m Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT id, username FROM users"); ResultSetMetaData metadata = resultSet.getMetaData(); int nullability = metadata.isNullable(1); if (nullability == ResultSetMetaData.columnNullable) { System.out.println("Columns ID can have a null value"); } else if (nullability == ResultSetMetaData.columnNoNulls) { System.out.println("Columns ID does not allowed to have a null value"); } else if (nullability == ResultSetMetaData.columnNullableUnknown) { System.out.println("Nullability unknown"); } }
From source file:ch.cern.db.flume.sink.kite.util.InferSchemaFromTable.java
public Schema getSchema() throws SQLException { FieldAssembler<Schema> builder = SchemaBuilder.record("log").fields(); Connection connection = DriverManager.getConnection(connection_url, connection_user, connection_password); Statement statement = connection.createStatement(); String query = "SELECT * " + "FROM " + tableName + " WHERE 0=1"; LOG.info("Running query for obtaining metadata: " + query); ResultSet result = statement.executeQuery(query); ResultSetMetaData metadata = result.getMetaData(); int columnCount = metadata.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = metadata.getColumnName(i); int columnType = metadata.getColumnType(i); boolean nullable = metadata.isNullable(i) != ResultSetMetaData.columnNoNulls; FieldTypeBuilder<Schema> field = builder.name(columnName).doc("SQL type: " + columnType).type(); switch (columnType) { case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: case java.sql.Types.INTEGER: case java.sql.Types.BIGINT: if (nullable) field.nullable().intType().noDefault(); else//from ww w.j a va 2s . co m field.intType().noDefault(); break; case java.sql.Types.BOOLEAN: if (nullable) field.nullable().booleanType().noDefault(); else field.booleanType().noDefault(); break; case java.sql.Types.NUMERIC: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: if (nullable) field.nullable().doubleType().noDefault(); else field.doubleType().noDefault(); break; case java.sql.Types.TIMESTAMP: case -101: //TIMESTAMP(3) WITH TIME ZONE case -102: //TIMESTAMP(6) WITH LOCAL TIME ZONE default: if (nullable) field.nullable().stringType().noDefault(); else field.stringType().noDefault(); break; } } return builder.endRecord(); }
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" : "")); }// w ww . ja v a 2 s .co m return list.toString(); }
From source file:org.apache.phoenix.coprocessor.MetaDataEndpointImpl.java
@SuppressWarnings("deprecation") private void addColumnToTable(List<Cell> results, PName colName, PName famName, Cell[] colKeyValues, List<PColumn> columns, boolean isSalted) { int i = 0;//from w w w. ja v a 2 s . co m int j = 0; while (i < results.size() && j < COLUMN_KV_COLUMNS.size()) { Cell kv = results.get(i); Cell searchKv = COLUMN_KV_COLUMNS.get(j); int cmp = Bytes.compareTo(kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength(), searchKv.getQualifierArray(), searchKv.getQualifierOffset(), searchKv.getQualifierLength()); if (cmp == 0) { colKeyValues[j++] = kv; i++; } else if (cmp > 0) { colKeyValues[j++] = null; } else { i++; // shouldn't happen - means unexpected KV in system table column row } } if (colKeyValues[DATA_TYPE_INDEX] == null || colKeyValues[NULLABLE_INDEX] == null || colKeyValues[ORDINAL_POSITION_INDEX] == null) { throw new IllegalStateException( "Didn't find all required key values in '" + colName.getString() + "' column metadata row"); } Cell columnSizeKv = colKeyValues[COLUMN_SIZE_INDEX]; Integer maxLength = columnSizeKv == null ? null : PDataType.INTEGER.getCodec().decodeInt(columnSizeKv.getValueArray(), columnSizeKv.getValueOffset(), SortOrder.getDefault()); Cell decimalDigitKv = colKeyValues[DECIMAL_DIGITS_INDEX]; Integer scale = decimalDigitKv == null ? null : PDataType.INTEGER.getCodec().decodeInt(decimalDigitKv.getValueArray(), decimalDigitKv.getValueOffset(), SortOrder.getDefault()); Cell ordinalPositionKv = colKeyValues[ORDINAL_POSITION_INDEX]; int position = PDataType.INTEGER.getCodec().decodeInt(ordinalPositionKv.getValueArray(), ordinalPositionKv.getValueOffset(), SortOrder.getDefault()) + (isSalted ? 1 : 0); Cell nullableKv = colKeyValues[NULLABLE_INDEX]; boolean isNullable = PDataType.INTEGER.getCodec().decodeInt(nullableKv.getValueArray(), nullableKv.getValueOffset(), SortOrder.getDefault()) != ResultSetMetaData.columnNoNulls; Cell dataTypeKv = colKeyValues[DATA_TYPE_INDEX]; PDataType dataType = PDataType.fromTypeId(PDataType.INTEGER.getCodec().decodeInt(dataTypeKv.getValueArray(), dataTypeKv.getValueOffset(), SortOrder.getDefault())); if (maxLength == null && dataType == PDataType.BINARY) dataType = PDataType.VARBINARY; // For // backward // compatibility. Cell sortOrderKv = colKeyValues[SORT_ORDER_INDEX]; SortOrder sortOrder = sortOrderKv == null ? SortOrder.getDefault() : SortOrder.fromSystemValue(PDataType.INTEGER.getCodec().decodeInt(sortOrderKv.getValueArray(), sortOrderKv.getValueOffset(), SortOrder.getDefault())); Cell arraySizeKv = colKeyValues[ARRAY_SIZE_INDEX]; Integer arraySize = arraySizeKv == null ? null : PDataType.INTEGER.getCodec().decodeInt(arraySizeKv.getValueArray(), arraySizeKv.getValueOffset(), SortOrder.getDefault()); Cell viewConstantKv = colKeyValues[VIEW_CONSTANT_INDEX]; byte[] viewConstant = viewConstantKv == null ? null : viewConstantKv.getValue(); Cell isViewReferencedKv = colKeyValues[IS_VIEW_REFERENCED_INDEX]; boolean isViewReferenced = isViewReferencedKv != null && Boolean.TRUE.equals(PDataType.BOOLEAN.toObject(isViewReferencedKv.getValueArray(), isViewReferencedKv.getValueOffset(), isViewReferencedKv.getValueLength())); PColumn column = new PColumnImpl(colName, famName, dataType, maxLength, scale, isNullable, position - 1, sortOrder, arraySize, viewConstant, isViewReferenced); columns.add(column); }
From source file:org.ensembl.healthcheck.util.DBUtils.java
/** * Check if there are any blank entires in a column that is not supposed to * be null.// w ww . ja v a 2 s . c om * * @param con * The database connection to use. * @param table * The table to use. * @param column * The column to examine. * @return An list of the row indices of any blank entries. Will be * zero-length if there are none. */ public static List<String> checkBlankNonNull(Connection con, String table, String column) { if (con == null) { logger.severe("checkBlankNonNull (column): Database connection is null"); return null; } List<String> blanks = new ArrayList<String>(); Statement stmt = null; ResultSet rs = null; try { String sql = "SELECT " + column + " FROM " + table; stmt = con.createStatement(); rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { String columnValue = rs.getString(1); // should it be non-null? if (rsmd.isNullable(1) == ResultSetMetaData.columnNoNulls) { if (StringUtils.isEmpty(columnValue)) { blanks.add(Integer.toString(rs.getRow())); } } } rs.close(); stmt.close(); } catch (Exception e) { throw new SqlUncheckedException("Could not check blanks or nulls", e); } finally { closeQuietly(rs); closeQuietly(stmt); } return blanks; }
From source file:org.ensembl.healthcheck.util.DBUtils.java
/** * Check all columns of a table for blank entires in columns that are marked * as being NOT NULL./* w w w. j av a 2 s . c o m*/ * * @param con * The database connection to use. * @param table * The table to use. * @return The total number of blank null enums. */ public static int checkBlankNonNull(Connection con, String table) { if (con == null) { logger.severe("checkBlankNonNull (table): Database connection is null"); return 0; } int blanks = 0; String sql = "SELECT * FROM " + table; ResultSet rs = null; Statement stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { String columnValue = rs.getString(i); String columnName = rsmd.getColumnName(i); // should it be non-null? if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls) { if (columnValue == null || columnValue.equals("")) { blanks++; logger.warning("Found blank non-null value in column " + columnName + " in " + table); } } } // for column } } catch (Exception e) { throw new SqlUncheckedException("Could not check for blank non-nulls", e); } finally { closeQuietly(rs); closeQuietly(stmt); } return blanks; }
From source file:org.geoserver.taskmanager.tasks.CopyTableTaskTypeImpl.java
@Override public TaskResult run(TaskContext ctx) throws TaskException { // TODO: check for ctx.isInterruptMe() in loops and cancel task final DbSource sourcedb = (DbSource) ctx.getParameterValues().get(PARAM_SOURCE_DB_NAME); final DbSource targetdb = (DbSource) ctx.getParameterValues().get(PARAM_TARGET_DB_NAME); final DbTable table = (DbTable) ctx.getBatchContext().get(ctx.getParameterValues().get(PARAM_TABLE_NAME)); final DbTable targetTable = ctx.getParameterValues().containsKey(PARAM_TARGET_TABLE_NAME) ? (DbTable) ctx.getParameterValues().get(PARAM_TARGET_TABLE_NAME) : new DbTableImpl(targetdb, table.getTableName()); final String tempTableName = SqlUtil.qualified(SqlUtil.schema(targetTable.getTableName()), "_temp_" + UUID.randomUUID().toString().replace('-', '_')); ctx.getBatchContext().put(targetTable, new DbTableImpl(targetdb, tempTableName)); try (Connection sourceConn = sourcedb.getDataSource().getConnection()) { sourceConn.setAutoCommit(false); try (Connection destConn = targetdb.getDataSource().getConnection()) { try (Statement stmt = sourceConn.createStatement()) { stmt.setFetchSize(BATCH_SIZE); try (ResultSet rs = stmt .executeQuery("SELECT * FROM " + sourcedb.getDialect().quote(table.getTableName()))) { ResultSetMetaData rsmd = rs.getMetaData(); String tempSchema = SqlUtil.schema(tempTableName); String sqlCreateSchemaIfNotExists = tempSchema == null ? "" : targetdb.getDialect().createSchema(destConn, targetdb.getDialect().quote(tempSchema)); // create the temp table structure StringBuilder sb = new StringBuilder(sqlCreateSchemaIfNotExists); sb.append("CREATE TABLE ").append(targetdb.getDialect().quote(tempTableName)).append(" ( "); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = targetdb.getDialect().quote(rsmd.getColumnLabel(i)); String typeName = rsmd.getColumnTypeName(i); sb.append(columnName).append(" ").append(typeName); if (("char".equals(typeName) || "varchar".equals(typeName)) && rsmd.getColumnDisplaySize(i) > 0 && rsmd.getColumnDisplaySize(i) < Integer.MAX_VALUE) { sb.append(" (").append(rsmd.getColumnDisplaySize(i)).append(" ) "); }/*from w w w.ja va 2 s. com*/ switch (sourcedb.getDialect().isNullable(rsmd.isNullable(i))) { case ResultSetMetaData.columnNoNulls: sb.append(" NOT NULL"); break; case ResultSetMetaData.columnNullable: sb.append(" NULL"); break; } sb.append(", "); } String primaryKey = getPrimaryKey(sourceConn, table.getTableName()); boolean hasPrimaryKeyColumn = !primaryKey.isEmpty(); if (!hasPrimaryKeyColumn) { // create a Primary key column if none exist. sb.append(GENERATE_ID_COLUMN_NAME + " int PRIMARY KEY, "); columnCount++; } sb.setLength(sb.length() - 2); sb.append(" ); "); // creating indexes Map<String, Set<String>> indexAndColumnMap = getIndexesColumns(sourceConn, table.getTableName()); Set<String> uniqueIndexes = getUniqueIndexes(sourceConn, table.getTableName()); Set<String> spatialColumns = sourcedb.getDialect().getSpatialColumns(sourceConn, table.getTableName(), sourcedb.getSchema()); for (String indexName : indexAndColumnMap.keySet()) { Set<String> columnNames = indexAndColumnMap.get(indexName); boolean isSpatialIndex = columnNames.size() == 1 && spatialColumns.contains(columnNames.iterator().next()); sb.append(targetdb.getDialect().createIndex(tempTableName, columnNames, isSpatialIndex, uniqueIndexes.contains(indexName))); } // we are copying a view and need to create the spatial index. if (indexAndColumnMap.isEmpty() && !spatialColumns.isEmpty()) { sb.append( targetdb.getDialect().createIndex(tempTableName, spatialColumns, true, false)); } String dump = sb.toString(); LOGGER.log(Level.FINE, "creating temporary table: " + dump); try (Statement stmt2 = destConn.createStatement()) { stmt2.executeUpdate(dump); } // copy the data sb = new StringBuilder("INSERT INTO ").append(targetdb.getDialect().quote(tempTableName)) .append(" VALUES ("); for (int i = 0; i < columnCount; i++) { if (i > 0) { sb.append(","); } sb.append("?"); } sb.append(")"); LOGGER.log(Level.FINE, "inserting records: " + sb.toString()); try (PreparedStatement pstmt = destConn.prepareStatement(sb.toString())) { int batchSize = 0; int primaryKeyValue = 0; while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { pstmt.setObject(i, rs.getObject(i)); } // generate the primary key value if (!hasPrimaryKeyColumn) { pstmt.setObject(columnCount, primaryKeyValue); } pstmt.addBatch(); batchSize++; if (batchSize >= BATCH_SIZE) { pstmt.executeBatch(); batchSize = 0; } primaryKeyValue++; } if (batchSize > 0) { pstmt.executeBatch(); } } } } } } catch (SQLException e) { // clean-up if necessary try (Connection conn = targetdb.getDataSource().getConnection()) { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("DROP TABLE IF EXISTS " + targetdb.getDialect().quote(tempTableName)); } } catch (SQLException e2) { } throw new TaskException(e); } return new TaskResult() { @Override public void commit() throws TaskException { try (Connection conn = targetdb.getDataSource().getConnection()) { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate( "DROP TABLE IF EXISTS " + targetdb.getDialect().quote(targetTable.getTableName())); stmt.executeUpdate("ALTER TABLE " + targetdb.getDialect().quote(tempTableName) + " RENAME TO " + targetdb.getDialect().quote(SqlUtil.notQualified(targetTable.getTableName()))); } ctx.getBatchContext().delete(targetTable); } catch (SQLException e) { throw new TaskException(e); } } @Override public void rollback() throws TaskException { try (Connection conn = targetdb.getDataSource().getConnection()) { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("DROP TABLE " + targetdb.getDialect().quote(tempTableName) + ""); } } catch (SQLException e) { throw new TaskException(e); } } }; }
From source file:org.rhq.plugins.postgres.PostgresTableComponent.java
private static boolean isNullableToBoolean(int isNullable) { return isNullable == ResultSetMetaData.columnNoNulls ? false : true; }
From source file:org.seasar.dbflute.logic.jdbc.metadata.synonym.DfSynonymExtractorOracle.java
protected List<DfColumnMeta> getSynonymColumns(Connection conn, UnifiedSchema synonymOwner, String synonymName) throws SQLException { final List<DfColumnMeta> columnList = new ArrayList<DfColumnMeta>(); Statement st = null;/*from ww w .j ava 2 s.co m*/ ResultSet rs = null; try { st = conn.createStatement(); final String synonymSqlName = synonymOwner.buildSchemaQualifiedName(synonymName); final String sql = "select * from " + synonymSqlName + " where 0=1"; rs = st.executeQuery(sql); final ResultSetMetaData metaData = rs.getMetaData(); int count = metaData.getColumnCount(); for (int i = 0; i < count; i++) { int index = i + 1; String columnName = metaData.getColumnName(index); int columnType = metaData.getColumnType(index); String columnTypeName = metaData.getColumnTypeName(index); int precision = metaData.getPrecision(index); int scale = metaData.getScale(index); int nullableType = metaData.isNullable(index); DfColumnMeta column = new DfColumnMeta(); column.setColumnName(columnName); column.setJdbcDefValue(columnType); column.setDbTypeName(columnTypeName); column.setColumnSize(precision); column.setDecimalDigits(scale); column.setRequired(nullableType == ResultSetMetaData.columnNoNulls); columnList.add(column); } return columnList; } finally { if (st != null) { try { st.close(); } catch (SQLException ignored) { } } if (rs != null) { try { rs.close(); } catch (SQLException ignored) { } } } }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Populates model with the query results. The query executed is the * currently selected query in the combo-box. * //from www . ja v a 2s. c om * @param rawSqlStatement * The SQL statement to execute * @param model * The model to populate with the results * @param tripleFile * The location to write the results to as triples. */ private void execute(String rawSqlStatement, ListTableModel<Object> model, File tripleFile) { String sqlStatement = rawSqlStatement; Statement stmt = null; ResultSet result = null; ResultSetMetaData meta = null; List<Object> rowData = null; int retValue = 0; SQLWarning warning = null; int[] myType; Object value; String typeName; String colName; String metaName; boolean hasResults = false; boolean hasBLOB = false; Date connAsk = null; Date connGot = null; Date stmtGot = null; Date queryStart = null; Date queryReady = null; Date queryRSFetched = null; Date queryRSProcessed = null; long rows = 0; int cols = 0; boolean hasParams = false; final List<StatementParameter> allParams = new ArrayList<StatementParameter>(); List<Object> outParams = null; modeOfCurrentTable = whichModeValue(); mapOfCurrentTables = new HashMap<String, String>(); // Try to prevent incorrect selection of query type by checking // beginning of SQL statement for obvious stuff // First check "Select" and Describe query types if (!isOkayQueryType(getQuery().getSql())) { // If the query type is wrong, and the user doesn't override then // Get Out Of Here! return; } // If there were BLOB columns included in the last query the connection // will have been left open. Since we are executing a new query we // can close that old connection now. if (conn != null) { try { conn.close(); } catch (Throwable any) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error (expected) closing connection", any); } } } conn = null; try { messageOut(Resources.getString("msgExecuteQuery", asQuery.isSelected() ? Resources.getString("msgQuery") : asDescribe.isSelected() ? Resources.getString("msgDescribe") : Resources.getString("msgUpdate"), sqlStatement), STYLE_BOLD); if (poolConnect.isSelected()) { messageOut(Resources.getString("msgPoolStats") + " ", STYLE_SUBTLE, false); if (getDBPool() != null) { messageOut(Resources.getString("msgPoolStatsCount", getDBPool().getNumActive() + "", getDBPool().getNumIdle() + "")); LOGGER.debug("Retrieved existing DB connection pool"); } else { LOGGER.debug("No existing DB pool"); messageOut(Resources.getString("msgPoolNone")); } } if (getDBPool() == null || /* conn == null */ !((String) connectString.getEditor().getItem()).equals(lastConnection) || !userId.getText().equals(lastUserId) || !new String(password.getPassword()).equals(lastPassword)) { removeDBPool(); lastConnection = (String) connectString.getEditor().getItem(); lastUserId = userId.getText(); lastPassword = new String(password.getPassword()); if (poolConnect.isSelected()) { setupDBPool(lastConnection, lastUserId, lastPassword); } messageOut(Resources.getString("msgConnCreated", lastConnection, lastUserId), STYLE_SUBTLE); } connAsk = new java.util.Date(); if (poolConnect.isSelected()) { conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + DBPOOL_NAME); LOGGER.debug("Got pooled connection"); messageOut(Resources.getString("msgGotPoolConn"), STYLE_GREEN); } else { conn = DriverManager.getConnection(lastConnection, lastUserId, lastPassword); LOGGER.debug("Got non-pooled connection"); messageOut(Resources.getString("msgGotDirectConn"), STYLE_GREEN); } if (hasParams = sqlStatement.indexOf("$PARAM[") > -1) { sqlStatement = makeParams(sqlStatement, allParams); } connGot = new java.util.Date(); conn.setAutoCommit(autoCommit.isSelected()); conn.setReadOnly(readOnly.isSelected()); if (!hasParams) { stmt = conn.createStatement(); } else { stmt = conn.prepareCall(sqlStatement); setupCall((CallableStatement) stmt, allParams); } stmtGot = new java.util.Date(); try { if (!maxRows.getSelectedItem().equals(Resources.getString("proNoLimit"))) { stmt.setMaxRows(Integer.parseInt((String) maxRows.getSelectedItem())); messageOut("\n" + Resources.getString("msgMaxRows", stmt.getMaxRows() + ""), STYLE_SUBTLE); } } catch (Exception any) { LOGGER.warn("Unable to set maximum rows", any); messageOut(Resources.getString("errFailSetMaxRows", (String) maxRows.getSelectedItem(), any.getMessage()), STYLE_YELLOW); } if (asQuery.isSelected() || asDescribe.isSelected()) { queryStart = new java.util.Date(); if (!hasParams) { int updateCount; // Execute the query synchronously stmt.execute(sqlStatement); messageOut(Resources.getString("msgQueryExecutedByDB"), STYLE_GREEN); // Process the query results and/or report status if ((updateCount = stmt.getUpdateCount()) > -1) { do { LOGGER.debug("Looking for results [update=" + updateCount + "]"); stmt.getMoreResults(); } while ((updateCount = stmt.getUpdateCount()) > -1); } result = stmt.getResultSet(); } else { result = ((PreparedStatement) stmt).executeQuery(); } queryReady = new java.util.Date(); meta = result.getMetaData(); cols = meta.getColumnCount(); } else { queryStart = new java.util.Date(); if (!hasParams) { retValue = stmt.executeUpdate(sqlStatement); } else { retValue = ((PreparedStatement) stmt).executeUpdate(); } queryReady = new java.util.Date(); } if (asQuery.isSelected()) { for (int col = 0; col < cols; ++col) { colName = meta.getColumnName(col + 1); if (colName == null || colName.trim().length() == 0) { colName = Resources.getString("msgUnnamedColumn", meta.getColumnLabel(col + 1)); } if (configDisplayColumnDataType.isSelected()) { metaName = meta.getColumnTypeName(col + 1) + " " + meta.getColumnDisplaySize(col + 1) + " ("; // have had oracle tables report large precision values // for BLOB fields that caused exception to be thrown // by getPrecision() since the value was beyond int try { metaName += meta.getPrecision(col + 1); } catch (Exception any) { metaName += "?"; LOGGER.warn("Unable to get column precision", any); } metaName += "."; metaName += meta.getScale(col + 1); metaName += ")"; colName += " [" + metaName + "]"; } model.addColumn(colName); // Keep collection of tables used for Insert and Update Menu // Selections try { mapOfCurrentTables.put(meta.getTableName(col + 1), null); } catch (Exception any) { // Probably unimplemented method - Sybase driver LOGGER.warn("Failed to obtain table name from metadata", any); messageOut(Resources.getString("errFailReqTableName", any.getMessage()), STYLE_SUBTLE); } } rowData = new ArrayList<Object>(); myType = new int[cols]; for (int col = 0; col < cols; ++col) { typeName = meta.getColumnTypeName(col + 1).toUpperCase(); if (typeName.equals("NUMBER")) { if (meta.getScale(col + 1) > 0) { myType[col] = COLUMN_DATA_TYPE_DOUBLE; // DOUBLE } else if (meta.getPrecision(col + 1) <= MAX_DIGITS_FOR_INT) { myType[col] = COLUMN_DATA_TYPE_INT; // INTEGER } else { myType[col] = COLUMN_DATA_TYPE_LONG; // LONG } } else if (typeName.equals("LONG")) { myType[col] = COLUMN_DATA_TYPE_LONG; } else if (typeName.equals("DATETIME")) { myType[col] = COLUMN_DATA_TYPE_DATETIME; // Date/Time } else if (typeName.equals("DATE")) { myType[col] = COLUMN_DATA_TYPE_DATE; // Date/Time } else if (typeName.equals("BLOB")) { myType[col] = COLUMN_DATA_TYPE_BLOB; hasBLOB = true; } else { myType[col] = 0; // Default - String } } if (tripleFile != null) { try { final RdbToRdf exporter = new RdbToRdf(tripleFile.getAbsolutePath(), getQuery().getSql(), result); exporter.run(); rows = exporter.getLatestNumberOfRowsExported(); messageOut(""); messageOut(Resources.getString("msgEndExportToFile"), STYLE_BOLD); } catch (Throwable throwable) { messageOut(Resources.getString("errFailDataSave", throwable.toString()), STYLE_RED); LOGGER.error("Failed to save data to triples file: " + tripleFile.getAbsolutePath(), throwable); } } else if (fileLogResults.isSelected()) { writeDataAsCSV(sqlStatement, model, DBRESULTS_NAME, result, myType, false); } else { while (result.next()) { ++rows; rowData = new ArrayList<Object>(); for (int col = 0; col < cols; ++col) { value = getResultField(result, col + 1, myType[col]); rowData.add(value); } model.addRowFast(rowData); hasResults = true; } model.updateCompleted(); } queryRSProcessed = new java.util.Date(); } else if (asDescribe.isSelected()) { String colLabel; meta = result.getMetaData(); myType = new int[DESC_TABLE_COLUMN_COUNT]; for (int col = 0; col < DESC_TABLE_COLUMN_COUNT; ++col) { switch (col) { case DESC_TABLE_NAME_COLUMN: // Col Name colLabel = Resources.getString("proColumnName"); myType[col] = COLUMN_DATA_TYPE_STRING; break; case DESC_TABLE_TYPE_COLUMN: // Col Type colLabel = Resources.getString("proColumnType"); myType[col] = COLUMN_DATA_TYPE_STRING; break; case DESC_TABLE_LENGTH_COLUMN: // Col Length colLabel = Resources.getString("proColumnLength"); myType[col] = COLUMN_DATA_TYPE_INT; break; case DESC_TABLE_PRECISION_COLUMN: // Col precision colLabel = Resources.getString("proColPrecision"); myType[col] = COLUMN_DATA_TYPE_INT; break; case DESC_TABLE_SCALE_COLUMN: // Col scale colLabel = Resources.getString("proColScale"); myType[col] = COLUMN_DATA_TYPE_INT; break; case DESC_TABLE_NULLS_OK_COLUMN: // Nulls Okay? colLabel = Resources.getString("proColNullsAllowed"); myType[col] = COLUMN_DATA_TYPE_STRING; break; default: // oops colLabel = Resources.getString("proColUndefined"); break; } if (configDisplayColumnDataType.isSelected()) { colLabel += " ["; colLabel += myType[col] == 0 ? Resources.getString("proColCharType") : Resources.getString("proColNumeric"); colLabel += "]"; } model.addColumn(colLabel); } rowData = new ArrayList<Object>(); for (int col = 0; col < cols; ++col) { rowData = new ArrayList<Object>(); for (int row = 0; row < DESC_TABLE_COLUMN_COUNT; ++row) { switch (row) { case DESC_TABLE_NAME_COLUMN: // Name colName = meta.getColumnName(col + 1); if (colName == null || colName.trim().length() == 0) { colName = Resources.getString("msgUnnamedColumn", meta.getColumnLabel(col + 1)); } value = colName; break; case DESC_TABLE_TYPE_COLUMN: // Type value = meta.getColumnTypeName(col + 1) + " (" + meta.getColumnType(col + 1) + ")"; break; case DESC_TABLE_LENGTH_COLUMN: // Length value = new Integer(meta.getColumnDisplaySize(col + 1)); break; case DESC_TABLE_PRECISION_COLUMN: // Precision try { value = new Integer(meta.getPrecision(col + 1)); } catch (Exception any) { value = "?"; LOGGER.warn("Unable to obtain column precision", any); } break; case DESC_TABLE_SCALE_COLUMN: // Scale value = new Integer(meta.getScale(col + 1)); break; case DESC_TABLE_NULLS_OK_COLUMN: // Nulls Okay? value = meta.isNullable(col + 1) == ResultSetMetaData.columnNullable ? Resources.getString("proYes") : meta.isNullable(col + 1) == ResultSetMetaData.columnNoNulls ? Resources.getString("proNo") : Resources.getString("proUnknown"); break; default: value = null; break; } rowData.add(value); // Keep collection of tables used for Insert and Update Menu // Selections try { mapOfCurrentTables.put(meta.getTableName(col + 1), null); } catch (Exception any) { // Probably unimplemented method - Sybase driver LOGGER.warn("Failed to obtain table name from metadata", any); messageOut(Resources.getString("errFailReqTableName", any.getMessage()), STYLE_SUBTLE); } } model.addRow(rowData); } while (result.next()) { rows++; for (int col = 0; col < cols; ++col) { result.getObject(col + 1); } } queryRSFetched = new java.util.Date(); } else { messageOut("\n" + Resources.getString("msgReturnValue") + " " + retValue, STYLE_BOLD, false); rows = stmt.getUpdateCount(); } messageOut("\n" + Resources.getString("msgRows") + " ", STYLE_NORMAL, false); if (rows == stmt.getMaxRows() && rows > 0) { messageOut("" + rows, STYLE_YELLOW); } else { messageOut("" + rows, STYLE_BOLD); } messageOut(""); } catch (SQLException sql) { LOGGER.error("Error executing SQL", sql); messageOut(Resources.getString("errFailSQL", sql.getClass().getName(), sql.getMessage()), STYLE_RED); userMessage(Resources.getString("errFailSQLText", sql.getMessage()), Resources.getString("errFailSQLTitle"), JOptionPane.ERROR_MESSAGE); while ((sql = sql.getNextException()) != null) { LOGGER.error("Next Exception", sql); } modeOfCurrentTable = -1; } catch (Throwable any) { LOGGER.error("Error executing SQL", any); messageOut(Resources.getString("errFailSQL", any.getClass().getName(), any.getMessage()), STYLE_RED); userMessage(Resources.getString("errFailSQLText", any.getMessage()), Resources.getString("errFailSQLTitle"), JOptionPane.ERROR_MESSAGE); modeOfCurrentTable = -1; } finally { fileSaveBLOBs.setEnabled(hasBLOB); setExportAvailable((hasResults && model.getRowCount() > 0) || tripleFile != null); queryMakeInsert.setEnabled( modeOfCurrentTable == Query.MODE_DESCRIBE || modeOfCurrentTable == Query.MODE_QUERY); if (hasParams) { outParams = getOutParams((CallableStatement) stmt, allParams); } LOGGER.debug("Check for more results"); try { int resultCount = 0; while (stmt.getMoreResults()) { int updateCount; ++resultCount; updateCount = stmt.getUpdateCount(); LOGGER.debug("More results [" + resultCount + "][updateCount=" + updateCount + "]"); } } catch (SQLException sql) { LOGGER.error("Failed checking for more results", sql); messageOut(Resources.getString("errFailAddlResults", sql.getClass().getName(), sql.getMessage())); } LOGGER.debug("No more results"); if (result != null) { try { result.close(); LOGGER.info("Resultset closed"); } catch (Throwable any) { LOGGER.error("Unable to close resultset", any); } } if (stmt != null) { try { warning = stmt.getWarnings(); while (warning != null) { LOGGER.warn("Stmt Warning: " + warning.toString()); messageOut(Resources.getString("errStmtWarning", warning.toString()), STYLE_YELLOW); warning = warning.getNextWarning(); } } catch (Throwable any) { LOGGER.warn("Error retrieving statement SQL warnings", any); } try { stmt.close(); LOGGER.debug("Statement closed"); } catch (Throwable any) { LOGGER.error("Unable to close statement", any); } } if (conn != null) { try { warning = conn.getWarnings(); while (warning != null) { LOGGER.warn("Connt Warning: " + warning.toString()); messageOut(Resources.getString("errConnWarning", warning.toString()), STYLE_YELLOW); warning = warning.getNextWarning(); } } catch (Throwable any) { LOGGER.warn("Error retrieving connection SQL warnings", any); } } // Close the connection if there are no BLOBs. // If the user decides to save a BLOB we will need to DB connection // to remain open, hence we only close here if there are no BLOBs if (!hasBLOB && conn != null) { try { conn.close(); conn = null; LOGGER.debug("DB Connection closed"); } catch (Throwable any) { LOGGER.error("Unable to close DB connection", any); } } reportStats(sqlStatement, connAsk, connGot, stmtGot, queryStart, queryReady, queryRSFetched, queryRSProcessed, rows, cols, asDescribe.isSelected() ? model : null, outParams); // reportResults(SQL, model); } }