List of usage examples for java.sql ResultSetMetaData getColumnLabel
String getColumnLabel(int column) throws SQLException;
From source file:io.stallion.dataAccess.BeanListHandler.java
private String[] makeColumnToProperty(ResultSetMetaData rsmd, List<String> propertyNames) throws SQLException { int cols = rsmd.getColumnCount(); String[] columnToProperty = new String[cols + 1]; Arrays.fill(columnToProperty, ""); for (int col = 1; col <= cols; ++col) { String columnName = rsmd.getColumnLabel(col); if (null == columnName || 0 == columnName.length()) { columnName = rsmd.getColumnName(col); }/*w w w. ja v a 2 s. co m*/ for (int i = 0; i < propertyNames.size(); ++i) { String propertyName = propertyNames.get(i); if (propertyName.equalsIgnoreCase(columnName)) { columnToProperty[col] = propertyName; break; } } } return columnToProperty; }
From source file:com.opensource.dbhelp.dbutils.CamelBeanProcessor.java
/** * /*from ww w.j a v a 2 s . c o m*/ * * @param rsmd * * @param props * * @return ?? */ @Override protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException { int cols = rsmd.getColumnCount(); int columnToProperty[] = new int[cols + 1]; Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND); for (int col = 1; col <= cols; col++) { String columnName = rsmd.getColumnLabel(col); if (null == columnName || 0 == columnName.length()) { columnName = rsmd.getColumnName(col); } for (int i = 0; i < props.length; i++) { if (formatColName(columnName).equalsIgnoreCase(props[i].getName())) { columnToProperty[col] = i; break; } if (columnName.equalsIgnoreCase(props[i].getName())) { columnToProperty[col] = i; break; } } } return columnToProperty; }
From source file:org.hyperic.hq.product.JDBCQueryCache.java
private List getQueryColumns(ResultSet rs) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int size = rsmd.getColumnCount(); List rtn = new ArrayList(size); for (int i = 1; i <= size; i++) { rtn.add(rsmd.getColumnLabel(i)); }// w w w. j a va 2s . c om return rtn; }
From source file:jp.gr.java_conf.ka_ka_xyz.processor.AnnotationProcessor.java
@Override protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException { int cols = rsmd.getColumnCount(); int columnToProperty[] = new int[cols + 1]; Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND); for (int col = 1; col <= cols; col++) { String columnName = rsmd.getColumnLabel(col); for (int i = 0; i < props.length; i++) { if (equalsColumnAnnotation(columnName, props[i].getName())) { columnToProperty[col] = i; break; }//from ww w . jav a 2 s .c om } } return columnToProperty; }
From source file:jongo.handler.ResultSetMetaDataHandler.java
@Override public List<Row> handle(ResultSet rs) throws SQLException { List<Row> results = new ArrayList<Row>(); int rowId = 0; ResultSetMetaData metaData = rs.getMetaData(); Map<String, String> map = null; for (int i = 1; i <= metaData.getColumnCount(); i++) { map = new HashMap<String, String>(2); map.put("tableName", metaData.getTableName(i)); map.put("columnName", metaData.getColumnName(i)); map.put("columnLabel", metaData.getColumnLabel(i)); map.put("columnType", metaData.getColumnTypeName(i)); map.put("columnSize", String.valueOf(metaData.getColumnDisplaySize(i))); map.put("precision", String.valueOf(metaData.getPrecision(i))); map.put("scale", String.valueOf(metaData.getScale(i))); // map.put("catalog_name", metaData.getCatalogName(i)); // map.put("column_class_name", metaData.getColumnClassName(i)); // map.put("schema_name", metaData.getSchemaName(i)); // map.put("column_type", String.valueOf(metaData.getColumnType(i))); if (map != null) results.add(new Row(rowId++, map)); }/*from ww w .j a va 2s.c o m*/ return results; }
From source file:nl.b3p.viewer.util.databaseupdate.ScriptRunner.java
/** * Runs an SQL script (read in using the Reader parameter) using the * connection passed in// w ww .j a va 2s . co m * * @param conn - the connection to use for the script * @param reader - the source of the script * @throws SQLException if any SQL errors occur * @throws IOException if there is an error reading from the Reader */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { StringBuffer command = null; try { LineNumberReader lineReader = new LineNumberReader(reader); String line = null; while ((line = lineReader.readLine()) != null) { if (command == null) { command = new StringBuffer(); } String trimmedLine = line.trim(); if (trimmedLine.startsWith("--")) { log.debug(trimmedLine); } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) { // Do nothing } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) { // Do nothing } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); command.append(" "); Statement statement = conn.createStatement(); log.debug(command); boolean hasResults = false; if (stopOnError) { hasResults = statement.execute(command.toString()); } else { try { statement.execute(command.toString()); } catch (SQLException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); } } if (autoCommit && !conn.getAutoCommit()) { conn.commit(); } ResultSet rs = statement.getResultSet(); if (hasResults && rs != null) { ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); for (int i = 0; i < cols; i++) { String name = md.getColumnLabel(i); log.debug(name + "\t"); } while (rs.next()) { for (int i = 0; i < cols; i++) { String value = rs.getString(i); log.debug(value + "\t"); } } } command = null; try { statement.close(); } catch (Exception e) { // Ignore to workaround a bug in Jakarta DBCP } Thread.yield(); } else { command.append(line); command.append(" "); } } if (!autoCommit) { conn.commit(); } } catch (SQLException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); throw e; } catch (IOException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); throw e; } finally { if (!this.autoCommit) { conn.rollback(); } } }
From source file:de.tudarmstadt.ukp.csniper.ml.JdbcCustomReader.java
private void query() { try {/*from ww w .j a v a 2 s . com*/ Statement statement = sqlConnection.createStatement(); // execute query which sets user variables Iterator<String> it = Arrays.asList(StringUtils.split(setterQuery, "\n")).iterator(); StringBuilder sb = new StringBuilder(); while (it.hasNext()) { String line = it.next(); if (line.trim().startsWith("#")) { continue; } else if (line.trim().endsWith(";")) { sb.append(line); statement.addBatch(sb.toString()); sb = new StringBuilder(); } else { sb.append(line); } } statement.executeBatch(); statement.executeQuery(query); resultSet = statement.getResultSet(); resultSet.last(); resultSetSize = resultSet.getRow(); resultSet.beforeFirst(); completed = 0; // Store available column names columnNames = new HashSet<String>(); ResultSetMetaData meta = resultSet.getMetaData(); for (int i = 1; i < meta.getColumnCount() + 1; i++) { String columnName = meta.getColumnLabel(i); columnNames.add(columnName); if (!CAS_COLUMNS.contains(columnName)) { getLogger().warn("Unknown column [" + columnName + "]."); } } } catch (SQLException e) { throw new RuntimeException("There was an unrecoverable error executing the specified SQL statement.", e); } }
From source file:org.guzz.orm.mapping.POJOBasedObjectMapping.java
/**?@rs??Object * @throws SQLException *///from w w w . j a v a 2 s .co m public Object rs2Object(ResultSet rs, Class resultClass) throws SQLException { boolean isMap = false; BeanWrapper bw = this.beanWrapper; Object instance = resultClass == null ? proxyDomainObject() : BeanCreator.newBeanInstance(resultClass); if (instance instanceof Map) { isMap = true; } else { bw = resultClass == null ? this.beanWrapper : BeanWrapper.createPOJOWrapper(resultClass); } if (instance instanceof GuzzProxy) { ((GuzzProxy) instance).markReading(); } Table t = getTable(); ResultSetMetaData meta = rs.getMetaData(); int count = meta.getColumnCount(); for (int i = 1; i <= count; i++) { String colName = meta.getColumnLabel(i); TableColumn col = t.getColumnByColNameInRS(colName); ColumnORM orm = col != null ? col.getOrm() : null; if (orm != null) { // Object value = orm.loadResult(rs, instance, i); if (isMap) { ((Map) instance).put(col.getPropName(), value); } else { bw.setValue(instance, col.getPropName(), value); } } else if (resultClass != null) { //resultClass?resultClass?resultClass??? //resultClass?resultClass???IBatis Object value = rs.getObject(i); if (isMap) { ((Map) instance).put(colName, value); } else { bw.setValue(instance, colName, value); } } else { //SQL?Bean. -by String propName = getPropName(colName, bw); if (isMap) { ((Map) instance).put(propName == null ? colName : propName, rs.getObject(i)); } else { if (propName != null) { String typeName = bw.getPropertyTypeName(propName); SQLDataType sqlType = getDbGroup().getDialect().getDataType(typeName); Object value = sqlType.getSQLValue(rs, i); bw.setValue(instance, propName, value); } else { //TODO: business?debug?DebugService?? if (log.isDebugEnabled()) { log.debug("warning:ignore ResultSet column:[" + colName + "] in POJOBasedObjectMapping for business:[" + this.business.getName() + "]."); } } } } } if (instance instanceof GuzzProxy) { ((GuzzProxy) instance).unmarkReading(); } return instance; }
From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java
@PageableDefaults(pageNumber = 0, value = 10) @RequestMapping(value = "/sql", method = RequestMethod.POST) public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) { model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em)); String lowerCaseSQL = sql.trim().toLowerCase(); final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update") || lowerCaseSQL.startsWith("delete"); final boolean isDQL = lowerCaseSQL.startsWith("select"); if (!isDML && !isDQL) { model.addAttribute(Constants.ERROR, "SQL????insert?update?delete?select"); return showSQLForm(); }//from ww w. j a v a2 s . com try { new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { if (isDML) { Query query = em.createNativeQuery(sql); int updateCount = query.executeUpdate(); model.addAttribute("updateCount", updateCount); } else { String findSQL = sql; String countSQL = "select count(*) count from (" + findSQL + ") o"; Query countQuery = em.createNativeQuery(countSQL); Query findQuery = em.createNativeQuery(findSQL); findQuery.setFirstResult(pageable.getOffset()); findQuery.setMaxResults(pageable.getPageSize()); Page page = new PageImpl(findQuery.getResultList(), pageable, ((BigInteger) countQuery.getSingleResult()).longValue()); model.addAttribute("resultPage", page); em.unwrap(Session.class).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql); ResultSetMetaData metaData = psst.getMetaData(); List<String> columnNames = Lists.newArrayList(); for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) { columnNames.add(metaData.getColumnLabel(i)); } psst.close(); model.addAttribute("columnNames", columnNames); } }); } return null; } }); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); model.addAttribute(Constants.ERROR, sw.toString()); } return showSQLForm(); }
From source file:uk.ac.kcl.rowmappers.DocumentRowMapper.java
private void mapDBFields(Document doc, ResultSet rs) throws SQLException, IOException { //add additional query fields for ES export ResultSetMetaData meta = rs.getMetaData(); int colCount = meta.getColumnCount(); for (int col = 1; col <= colCount; col++) { Object value = rs.getObject(col); if (value != null) { String colLabel = meta.getColumnLabel(col).toLowerCase(); if (!fieldsToIgnore.contains(colLabel)) { DateTime dateTime;//from w w w .j a va 2s . c o m //map correct SQL time types switch (meta.getColumnType(col)) { case 91: Date dt = (Date) value; dateTime = new DateTime(dt.getTime()); doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), eSCompatibleDateTimeFormatter.print(dateTime)); break; case 93: Timestamp ts = (Timestamp) value; dateTime = new DateTime(ts.getTime()); doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), eSCompatibleDateTimeFormatter.print(dateTime)); break; default: doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), rs.getString(col)); break; } } } //map binary content from FS or database if required (as per docman reader) if (value != null && meta.getColumnLabel(col).equalsIgnoreCase(binaryContentFieldName)) { switch (binaryContentSource) { case "database": doc.setBinaryContent(rs.getBytes(col)); break; case "fileSystemWithDBPath": Resource resource = context.getResource(pathPrefix + rs.getString(col)); doc.setBinaryContent(IOUtils.toByteArray(resource.getInputStream())); break; default: break; } } } }