List of usage examples for java.sql ResultSetMetaData getColumnName
String getColumnName(int column) throws SQLException;
From source file:com.jaspersoft.jasperserver.war.CSVServlet.java
private void printCSV(ResultSet rs, PrintWriter out) throws Exception { ResultSetMetaData md = rs.getMetaData(); int numCols = md.getColumnCount(); // print column headers for (int i = 1; i < numCols; i++) { out.write(quoteString(md.getColumnName(i))); out.write(SEP);/*from w w w . jav a 2 s . c om*/ } out.write(quoteString(md.getColumnName(numCols))); out.write(NEWLINE); // print row data while (rs.next()) { for (int i = 1; i < numCols; i++) { out.write(quoteString("" + rs.getObject(i))); out.write(SEP); } out.write(quoteString("" + rs.getObject(numCols))); out.write(NEWLINE); } }
From source file:com.flexive.core.search.genericSQL.GenericSQLForeignTableSelector.java
protected GenericSQLForeignTableSelector(String mainColumn, String tableName, String linksOn, boolean hasTranslationTable, String translatedColumn) { FxSharedUtils.checkParameterNull(tableName, "tableName"); FxSharedUtils.checkParameterNull(linksOn, "linksOn"); Connection con = null;// w w w. j a v a 2 s .c om Statement stmt = null; this.tableName = tableName; this.linksOn = linksOn; this.mainColumn = mainColumn; this.hasTranslationTable = hasTranslationTable; this.translatedColumn = translatedColumn != null ? translatedColumn.toUpperCase() : null; try { con = Database.getDbConnection(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + StorageManager.getLimit(false, 0)); ResultSetMetaData md = rs.getMetaData(); for (int pos = 1; pos <= md.getColumnCount(); pos++) { String columnName = md.getColumnName(pos); FxDataType columnType; switch (md.getColumnType(pos)) { case java.sql.Types.CHAR: if (md.getPrecision(pos) == 1) { columnType = FxDataType.Boolean; //oracle break; } case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.CLOB: columnType = FxDataType.String1024; break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: columnType = FxDataType.Boolean; break; case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: columnType = FxDataType.Number; break; case java.sql.Types.DECIMAL: columnType = FxDataType.Double; break; case java.sql.Types.FLOAT: columnType = FxDataType.Float; break; case java.sql.Types.NUMERIC: case java.sql.Types.BIGINT: if ("CREATED_AT".equalsIgnoreCase(columnName) || "MODIFIED_AT".equalsIgnoreCase(columnName)) columnType = FxDataType.DateTime; else if ("CAT_TYPE".equals(columnName) && "FXS_ACL".equals(tableName)) { columnType = FxDataType.Number; } else columnType = FxDataType.LargeNumber; break; case java.sql.Types.DATE: columnType = FxDataType.Date; break; case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: columnType = FxDataType.DateTime; break; default: if (LOG.isInfoEnabled()) { LOG.info("Assigning String to " + tableName + "." + columnName + " found type=" + md.getColumnType(pos)); } columnType = FxDataType.String1024; } columns.put(columnName.toUpperCase(), columnType); } } catch (Throwable t) { @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) FxSqlSearchException ex = new FxSqlSearchException(LOG, "ex.sqlSearch.fieldSelector.initializeFailed", tableName, t.getMessage()); LOG.error(ex.getMessage(), ex); throw ex.asRuntimeException(); } finally { Database.closeObjects(GenericSQLForeignTableSelector.class, con, stmt); } }
From source file:db.migration.V055__UpdateECTS.java
public void migrate(JdbcTemplate jdbcTemplate) throws Exception { LOG.info("migrate()..."); // Get all organisaatiometadatas where there are strings to process List<Map> resultSet = jdbcTemplate.query( "SELECT id,hakutoimistoectsemail,hakutoimistoectsnimi,hakutoimistoectspuhelin,hakutoimistoectstehtavanimike FROM organisaatiometadata WHERE hakutoimistoectsemail<>'' OR hakutoimistoectsnimi<>'' OR hakutoimistoectspuhelin<>'' OR hakutoimistoectstehtavanimike<>''", new RowMapper<Map>() { @Override// w w w . j a v a 2 s. co m public Map mapRow(ResultSet rs, int rowNum) throws SQLException { Map r = new HashMap<String, Object>(); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 1; i <= metadata.getColumnCount(); i++) { String cname = metadata.getColumnName(i); int ctype = metadata.getColumnType(i); switch (ctype) { case Types.VARCHAR: // hakutoimistoectsemail,hakutoimistoectsnimi,hakutoimistoectspuhelin,hakutoimistoectstehtavanimike r.put(cname, rs.getString(cname)); break; case Types.BIGINT: // id r.put(cname, rs.getInt(cname)); break; default: break; } } LOG.debug(" read from db : organisaatiometadata = {}", r); return r; } }); // Move strings to monikielinenteksti_values for (Map orgmd : resultSet) { handleOrganisaatiometadata(orgmd, jdbcTemplate); } LOG.info("migrate()... done."); }
From source file:at.ac.univie.isc.asio.engine.sql.JooqEngineTest.java
@Test public void empty_select_to_webrowset_header() throws Exception { final Command params = CommandBuilder.empty().language(Language.SQL) .single(JooqEngine.PARAM_QUERY, REFERENCE_EMPTY).accept(WEBROWSET_TYPE).build(); final byte[] raw = performInvocationWith(params); final WebRowSet wrs = parseWebRowSet(raw); assertThat(wrs.size(), is(0));/*from w ww.j av a 2s . c o m*/ final ResultSetMetaData context = wrs.getMetaData(); for (int index = 0; index < COLUMN_NAMES.length; index++) { assertThat(context.getColumnName(index + 1), is(COLUMN_NAMES[index])); } }
From source file:org.apache.zeppelin.hive.HiveInterpreter.java
private InterpreterResult executeSql(String sql) { try {/*from w ww . j a va 2 s .c om*/ if (exceptionOnConnect != null) { return new InterpreterResult(Code.ERROR, exceptionOnConnect.getMessage()); } currentStatement = jdbcConnection.createStatement(); StringBuilder msg = null; if (StringUtils.containsIgnoreCase(sql, "EXPLAIN ")) { //return the explain as text, make this visual explain later msg = new StringBuilder(); } else { msg = new StringBuilder("%table "); } ResultSet res = currentStatement.executeQuery(sql); try { ResultSetMetaData md = res.getMetaData(); for (int i = 1; i < md.getColumnCount() + 1; i++) { if (i == 1) { msg.append(md.getColumnName(i)); } else { msg.append("\t" + md.getColumnName(i)); } } msg.append("\n"); while (res.next()) { for (int i = 1; i < md.getColumnCount() + 1; i++) { msg.append(res.getString(i) + "\t"); } msg.append("\n"); } } finally { try { res.close(); currentStatement.close(); } finally { currentStatement = null; } } InterpreterResult rett = new InterpreterResult(Code.SUCCESS, msg.toString()); return rett; } catch (SQLException ex) { logger.error("Can not run " + sql, ex); return new InterpreterResult(Code.ERROR, ex.getMessage()); } }
From source file:com.arsmentis.cordova.jdbc.Jdbc.java
private JSONArray execute(String sql) throws SQLException, JSONException { if (connection == null) { throw new SQLException("Not connected"); }//w w w. j a va 2 s .c o m JSONArray results = new JSONArray(); Statement statement = connection.createStatement(); if (statement.execute(sql)) { ResultSet resultSet = statement.getResultSet(); ResultSetMetaData columns = resultSet.getMetaData(); while (resultSet.next()) { JSONObject row = new JSONObject(); for (int i = 1; i <= columns.getColumnCount(); i++) { row.put(columns.getColumnName(i), resultSet.getObject(i)); } results.put(row); } resultSet.close(); } statement.close(); return results; }
From source file:com.chiorichan.account.adapter.sql.SqlAdapter.java
@Override public AccountMetaData readAccount(String id) throws LoginException { try {/* www . j a va 2 s . c om*/ AccountMetaData meta = new AccountMetaData(); if (id == null || id.isEmpty()) throw new LoginException(LoginExceptionReason.emptyUsername); Set<String> accountFieldSet = new HashSet<String>(accountFields); Set<String> accountColumnSet = new HashSet<String>(); accountFieldSet.add("acctId"); accountFieldSet.add("username"); ResultSet rs = sql.query("SELECT * FROM `" + table + "` LIMIT 0;"); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); do { for (int i = 1; i < columnCount + 1; i++) { accountColumnSet.add(rsmd.getColumnName(i)); } } while (rs.next()); String additionalAccountFields = ""; for (String f : accountFieldSet) { if (!f.isEmpty()) if (accountColumnSet.contains(f)) additionalAccountFields += " OR `" + f + "` = '" + id + "'"; else for (String c : accountColumnSet) { if (c.equalsIgnoreCase(f)) { additionalAccountFields += " OR `" + c + "` = '" + id + "'"; break; } } } rs = sql.query("SELECT * FROM `" + table + "` WHERE " + additionalAccountFields.substring(4) + ";"); if (rs == null || sql.getRowCount(rs) < 1) throw new LoginException(LoginExceptionReason.incorrectLogin); meta.setAll(DatabaseEngine.convertRow(rs)); meta.set("displayName", (rs.getString("fname").isEmpty()) ? rs.getString("name") : rs.getString("fname") + " " + rs.getString("name")); return meta; } catch (SQLException e) { throw new LoginException(e); } }
From source file:edu.stanford.junction.sample.sql.QueryHandler.java
@Override public void onMessageReceived(MessageHeader header, JSONObject message) { //String query = q.getQueryText(); String query = message.optString("query"); query = query.toLowerCase();/* ww w. jav a 2s .c o m*/ if (!query.contains("select")) return; if (query.contains("drop") || query.contains("delete")) return; System.out.println("Got query: " + query); Connection connection = null; try { // Load the JDBC driver String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver Class.forName(driverName); // Create a connection to the database //String serverName = "192.168.1.122"; String serverName = "127.0.0.1"; String mydatabase = "jinzora3"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url String username = "jinzora"; String password = "jinzora"; connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver e.printStackTrace(); } catch (SQLException e) { // Could not connect to the database e.printStackTrace(); } try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsMetaData = rs.getMetaData(); int cols = rsMetaData.getColumnCount(); while (rs.next()) { JSONObject row = new JSONObject(); try { for (int i = 1; i <= cols; i++) { // stupid indexing row.put(rsMetaData.getColumnName(i), rs.getObject(i)); } } catch (JSONException e) { e.printStackTrace(); } System.out.println("sending " + row); if (mActor != null) { //mActor.getJunction().sendMessageToTarget(header.getReplyTarget(),row); header.getReplyTarget().sendMessage(row); } } } catch (SQLException e) { e.printStackTrace(); } System.out.println("closing stream."); //results.close(); }
From source file:user.Query.java
public DefaultPieDataset getBlijdorpTweets() { query = " SELECT " + " (" + " SELECT count(*) " + " FROM Tweet " + " WHERE AREA != ' no area' " + " AND ANIMAL = ' no animal' " + " AND User_name = ' Diergaarde Blijdorp'" + " AND " + time + " ) AS Tweets_About_Areas, (" + " SELECT count(*) " + " FROM Tweet " + " WHERE ANIMAL != ' no animal' " + " AND User_name = ' Diergaarde Blijdorp' " + " AND " + time + " ) AS Tweets_About_Animals," + " (" + " SELECT count(*) " + " FROM Tweet " + " WHERE ANIMAL = ' no animal' " + " AND AREA = ' no area' " + " AND User_name = ' Diergaarde Blijdorp' " + " AND " + time + " ) AS 'Other_Tweets'" + " ;"; DefaultPieDataset dataset = new DefaultPieDataset(); try {/*from ww w . j a va 2s . c o m*/ ResultSet resultSet = executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); while (resultSet.next()) { int count = metaData.getColumnCount(); for (int i = 1; i <= count; i++) { dataset.setValue(metaData.getColumnName(i), Integer.parseInt(resultSet.getString(i))); } } } catch (SQLException ex) { } return dataset; }
From source file:com.netspective.axiom.sql.ResultSetUtils.java
/** * Given a ResultSet, return a Map of all the column names in the ResultSet * in lowercase as the key and the index of the column as the value. *///from w w w . j a v a 2 s .c o m public Map getColumnNamesIndexMap(ResultSet rs) throws SQLException { Map map = new HashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int colsCount = rsmd.getColumnCount(); for (int i = 1; i <= colsCount; i++) { map.put(rsmd.getColumnName(i).toLowerCase(), new Integer(i)); } return map; }