List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:Professor.java
public void checkData(String sql) throws Exception { ResultSet rs = st.executeQuery(sql); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 0; i < metadata.getColumnCount(); i++) { System.out.print("\t"+ metadata.getColumnLabel(i + 1)); }/*w w w .j a v a 2 s . c om*/ System.out.println("\n----------------------------------"); while (rs.next()) { for (int i = 0; i < metadata.getColumnCount(); i++) { Object value = rs.getObject(i + 1); if (value == null) { System.out.print("\t "); } else { System.out.print("\t"+value.toString().trim()); } } System.out.println(""); } }
From source file:kr.co.bitnine.octopus.testutils.MemoryDatabaseTest.java
private void verifyTableEquals(JSONObject expectedTable, ResultSet actualRows) throws Exception { ResultSetMetaData actualRowsMetaData = actualRows.getMetaData(); JSONArray expectedSchema = (JSONArray) expectedTable.get("table-schema"); assertEquals(expectedSchema.size(), actualRowsMetaData.getColumnCount()); for (int i = 0; i < expectedSchema.size(); i++) assertEquals(expectedSchema.get(i), actualRowsMetaData.getColumnName(i + 1)); for (Object rowObj : (JSONArray) expectedTable.get("table-rows")) { JSONArray row = (JSONArray) rowObj; actualRows.next();//from w ww . j a v a 2 s . c o m for (int i = 0; i < row.size(); i++) { Object expected = row.get(i); Object actual; int sqlType = actualRowsMetaData.getColumnType(i + 1); switch (sqlType) { case Types.INTEGER: if (expected instanceof Boolean) expected = (long) ((Boolean) expected ? 1 : 0); actual = actualRows.getLong(i + 1); break; case Types.NULL: case Types.FLOAT: case Types.VARCHAR: actual = actualRows.getObject(i + 1); break; default: throw new RuntimeException("java.sql.Types " + sqlType + " is not supported"); } assertEquals(expected, actual); } } assertFalse(actualRows.next()); }
From source file:org.apereo.services.persondir.support.jdbc.ColumnMapParameterizedRowMapper.java
@Override public final Map<String, Object> mapRow(final ResultSet rs, final int rowNum) throws SQLException { final ResultSetMetaData rsmd = rs.getMetaData(); final int columnCount = rsmd.getColumnCount(); final Map<String, Object> mapOfColValues = this.createColumnMap(columnCount); for (int i = 1; i <= columnCount; i++) { final String columnName = JdbcUtils.lookupColumnName(rsmd, i); final Object obj = this.getColumnValue(rs, i); if (!this.ignoreNull || obj != null) { final String key = this.getColumnKey(columnName); mapOfColValues.put(key, obj); }/*from w w w . ja va 2 s . c o m*/ } return mapOfColValues; }
From source file:com.linuxrouter.netcool.session.QueryUtils.java
public ArrayList<HashMap<String, Object>> executeQuery(String dbName, String sql) { Long start = System.currentTimeMillis(); ArrayList<HashMap<String, Object>> result = new ArrayList<>(); HashMap<Integer, String> colTypes = new HashMap<Integer, String>(); HashMap<Integer, String> colNames = new HashMap<Integer, String>(); try {/*from w ww. j a v a 2 s . co m*/ //connection caching... Connection con = null; if (connectionMap.get(dbName) == null) { BasicDataSource ds = DbUtils.getSimpleDataSourceByName(dbName); con = ds.getConnection(); connectionMap.put(dbName, con); } else { con = connectionMap.get(dbName); } Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); ResultSetMetaData metaData = rs.getMetaData(); int colCount = metaData.getColumnCount(); for (int i = 1; i <= colCount; i++) { colTypes.put(i, metaData.getColumnTypeName(i)); colNames.put(i, metaData.getColumnLabel(i)); } while (rs.next()) { HashMap<String, Object> dado = new HashMap<>(); for (int i = 1; i <= colCount; i++) { dado.put(colNames.get(i), rs.getObject(i)); } result.add(dado); } rs.close(); st.close(); //con.close(); Long end = System.currentTimeMillis(); //logger.debug("Query on external DB took: " + (end - start) + "ms"); } catch (SQLException ex) { logger.error("Erro ao executar query:", ex); } return result; }
From source file:net.orpiske.ssps.common.repository.search.cache.MultiRsHandler.java
@Override protected PackageInfo handleRow(ResultSet rs) throws SQLException { PackageInfo dto = new PackageInfo(); ResultSetMetaData meta = rs.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) { Object value = rs.getObject(i); String name = meta.getColumnName(i); try {/*from w ww .j a v a 2s. c o m*/ /* * We convert the column name to a more appropriate and java like name * because some columns are usually named as some_thing whereas Java * properties are named someThing. This call does this conversion. */ String javaProperty = NameConverter.sqlToProperty(name); if (javaProperty.equals("version")) { Version version = Version.toVersion((String) value); PropertyUtils.setSimpleProperty(dto, javaProperty, version); } else { PropertyUtils.setSimpleProperty(dto, javaProperty, value); } } catch (Exception e) { throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e); } } return dto; }
From source file:ResultsDecoratorText.java
public void write(ResultSet rs) throws IOException, SQLException { ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); for (int i = 1; i <= cols; i++) { print(md.getColumnName(i) + "\t"); }/* ww w . j av a 2 s . co m*/ println(); while (rs.next()) { for (int i = 1; i <= cols; i++) { print(rs.getString(i) + "\t"); } println(); } }
From source file:idp.mysql_con.java
public void mysql_query() { mysql_conn();/* w w w .ja va 2 s .c o m*/ try { String sql = gui.jTextField1.getText(); Statement st = con.createStatement(); if (sql.toLowerCase().startsWith("select")) { ResultSet rs = st.executeQuery(sql); int col = rs.getMetaData().getColumnCount(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= col; i++) { sb.append(rs.getMetaData().getColumnName(i).toUpperCase() + "\t"); } sb.append("\n"); while (rs.next()) { for (int i = 1; i <= col; i++) { sb.append(rs.getString(i) + "\t"); } sb.append("\n"); } gui.jTextArea1.append(gui.getTimeStamp() + " <System>: Displaying results:\n" + sb); } else if (sql.toLowerCase().startsWith("create table")) { int update = st.executeUpdate(sql); if (update == 0) { gui.jTextArea1.append(gui.getTimeStamp() + " <System>: Table created successfully\n"); } else { gui.jTextArea1.append(gui.getTimeStamp() + " <System>: Table creation failed\n"); } } else if (sql.toLowerCase().startsWith("insert") || sql.toLowerCase().startsWith("update") || sql.toLowerCase().startsWith("delete")) { int update = st.executeUpdate(sql); if (update >= 1) { gui.jTextArea1.append(gui.getTimeStamp() + " <System>: Update completed successfully\n"); } else { gui.jTextArea1.append(gui.getTimeStamp() + " <System>: Update failed\n"); } } else gui.jTextArea1.append(gui.getTimeStamp() + "<System>: Unauthorized query\n"); } catch (SQLException s) { gui.jTextArea1.append(gui.getTimeStamp() + " <System>: SQL statement is not executed\n"); } }
From source file:io.github.huherto.springyRecords.PrintRowCallbackHandler.java
@Override public void processRow(ResultSet rs) throws SQLException { if (rsmd == null) { rsmd = rs.getMetaData(); }/* w ww. j a va 2 s . c o m*/ if (format != null) { Object args[] = new Object[rsmd.getColumnCount()]; for (int index = 1; index <= rsmd.getColumnCount(); index++) { Object obj = JdbcUtils.getResultSetValue(rs, index); args[index - 1] = obj; } writer.println(String.format(format, args)); } else { StringBuilder sb = new StringBuilder(); for (int index = 1; index <= rsmd.getColumnCount(); index++) { Object obj = JdbcUtils.getResultSetValue(rs, index); if (index > 1) { sb.append(", "); } sb.append(JdbcUtils.lookupColumnName(rsmd, index)); sb.append("="); sb.append(obj); } writer.println(sb.toString()); } writer.flush(); }
From source file:gov.va.vinci.leo.tools.db.LeoArrayListHandler.java
/** * Whole <code>ResultSet</code> handler. It produce <code>List</code> as * result. To convert individual rows into Java objects it uses * <code>handleRow(ResultSet)</code> method. * * @param rs <code>ResultSet</code> to process. * @return a list of all rows in the result set * @throws java.sql.SQLException error occurs * @see #handleRow(java.sql.ResultSet)//from w ww . ja v a 2 s.c om */ @Override public List<Object[]> handle(ResultSet rs) throws SQLException { //Stash the metadata and column names mResultSetMetaData = rs.getMetaData(); mColumnNames = new HashMap<String, Integer>(mResultSetMetaData.getColumnCount()); for (int i = 0; i < mResultSetMetaData.getColumnCount(); i++) { mColumnNames.put(mResultSetMetaData.getColumnName(i + 1).toLowerCase(), i); } //Return the list of Object[] representing the result set return super.handle(rs); }
From source file:com.chiorichan.database.DatabaseEngine.java
public static Map<String, Object> convertRow(ResultSet rs) throws SQLException { Map<String, Object> result = Maps.newLinkedHashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); for (int i = 1; i < numColumns + 1; i++) { String columnName = rsmd.getColumnName(i); // Loader.getLogger().info( "Column: " + columnName + " <-> " + rsmd.getColumnTypeName( i ) ); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { result.put(columnName, rs.getArray(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) // Sometimes tinyints are read as bits {// ww w . ja va2 s. com result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { result.put(columnName, rs.getBoolean(columnName)); } else if (rsmd.getColumnTypeName(i).contains("BLOB") || rsmd.getColumnType(i) == java.sql.Types.BINARY) { // BLOG = Max Length 65,535. Recommended that you use a LONGBLOG. byte[] bytes = rs.getBytes(columnName); result.put(columnName, bytes); /* * try * { * result.put( columnName, new String( bytes, "ISO-8859-1" ) ); * } * catch ( UnsupportedEncodingException e ) * { * e.printStackTrace(); * } */ } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { result.put(columnName, rs.getDouble(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { result.put(columnName, rs.getFloat(columnName)); } else if (rsmd.getColumnTypeName(i).equals("INT")) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { result.put(columnName, rs.getNString(columnName)); } else if (rsmd.getColumnTypeName(i).equals("VARCHAR")) { result.put(columnName, rs.getString(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { result.put(columnName, rs.getDate(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { result.put(columnName, rs.getTimestamp(columnName)); } else { result.put(columnName, rs.getObject(columnName)); } } return result; }