List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:com.opencsv.ResultSetHelperService.java
@Override public String[] getColumnNames(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); String[] nameArray = new String[metadata.getColumnCount()]; for (int i = 0; i < metadata.getColumnCount(); i++) { nameArray[i] = metadata.getColumnLabel(i + 1); }//from w w w. j ava 2 s.c o m return nameArray; }
From source file:com.job.portal.utils.AbstractDAO.java
protected JSONArray getJSONArray(ResultSet rs) throws SQLException, JSONException { JSONArray arr = new JSONArray(); JSONObject obj = null;/* w w w . j av a 2 s. co m*/ ResultSetMetaData rsmd = rs.getMetaData(); int size = rsmd.getColumnCount(); while (rs.next()) { obj = new JSONObject(); for (int i = 1; i <= size; i++) { obj.put(rsmd.getColumnName(i), rs.getString(i)); } arr.put(obj); } return arr; }
From source file:com.tesora.dve.sql.util.JdbcConnectionResourceResponse.java
private List<ResultRow> convertNativeResults(ResultSet mrs) throws Throwable { ResultSetMetaData rsmd = mrs.getMetaData(); ArrayList<ResultRow> converted = new ArrayList<ResultRow>(); while (mrs.next()) { ResultRow rr = new ResultRow(); for (int i = 0; i < rsmd.getColumnCount(); i++) { rr.addResultColumn(mrs.getObject(i + 1), mrs.wasNull()); }//from ww w .ja v a 2 s. c o m converted.add(rr); } return converted; }
From source file:ResultsDecoratorSQL.java
public void write(ResultSet rs) throws IOException, SQLException { ResultSetMetaData md = rs.getMetaData(); // This assumes you're not using a Join!! String tableName = md.getTableName(1); int cols = md.getColumnCount(); StringBuffer sb = new StringBuffer("insert into ").append(tableName).append("("); for (int i = 1; i <= cols; i++) { sb.append(md.getColumnName(i));//w w w . j av a 2 s . c o m if (i != cols) { sb.append(", "); } } sb.append(") values ("); String insertCommand = sb.toString(); while (rs.next()) { println(insertCommand); for (int i = 1; i <= cols; i++) { String tmp = rs.getString(i); if (rs.wasNull()) { print("null"); } else { int type = md.getColumnType(i); // Don't quote numeric types; quote all others for now. switch (type) { case Types.BIGINT: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.INTEGER: print(tmp); break; default: tmp = tmp.replaceAll("'", "''"); print("'" + tmp + "'"); } } if (i != cols) { print(", "); } } println(");"); } }
From source file:net.orpiske.ssps.common.registry.SoftwareInventoryRsHandler.java
@Override public SoftwareInventoryDto handle(ResultSet rs) throws SQLException { // No records to handle :O if (!rs.next()) { return null; }// www . jav a 2 s.co m ResultSetMetaData meta = rs.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) { Object value = rs.getObject(i); String name = meta.getColumnName(i); try { /* * 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: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//w ww . j a v a2s . c o 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:com.pankaj.GenericResource.java
/** * Retrieves representation of an instance of com.pankaj.GenericResource * * @return an instance of java.lang.String * @throws java.lang.ClassNotFoundException * @throws java.sql.SQLException/*from ww w . java2s .c o m*/ * @throws java.lang.InstantiationException * @throws java.lang.IllegalAccessException */ @GET @Path("/products") @Produces(MediaType.APPLICATION_JSON) public String getAllProducts() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { Statement smt = conn.createStatement(); ResultSet rs = smt.executeQuery("select * from product"); ResultSetMetaData rsmd = rs.getMetaData(); int col = rsmd.getColumnCount(); while (rs.next()) { product pro = new product(rs.getInt("productid"), rs.getString("name"), rs.getString("description"), rs.getInt("quantity")); products.add(pro); json = Json.createObjectBuilder().add("productID", rs.getInt("productID")) .add("name", rs.getString("name")).add("description", rs.getString("description")) .add("quantity", rs.getInt("quantity")); productarray.add(json); } String res = productarray.build().toString(); return res; }
From source file:com.xtesoft.xtecuannet.framework.templater.filler.utils.SQLScanner.java
public List<SQLField> getSQLFields(String tableName) { List<SQLField> fields = new ArrayList<SQLField>(0); PreparedStatement psta = null; try {/*from www. j a va2s .com*/ logger.info("Processing table: " + tableName); psta = getConnection().prepareStatement("select top 1 * from " + tableName); ResultSet rset = psta.executeQuery(); ResultSetMetaData metadata = rset.getMetaData(); int columnCount = metadata.getColumnCount(); for (int i = 1; i <= columnCount; i++) { SQLField field = new SQLField(metadata.getColumnName(i), metadata.getColumnType(i)); fields.add(field); } rset.close(); psta.close(); } catch (Exception e) { logger.error("Error getting fields for table: " + tableName, e); } return fields; }
From source file:net.orpiske.ssps.common.repository.search.cache.PackageCacheRsHandler.java
@Override public PackageInfo handle(ResultSet rs) throws SQLException { // No records to handle :O if (!rs.next()) { return null; }//from w w w . j a v a2 s . c o m ResultSetMetaData meta = rs.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) { Object value = rs.getObject(i); String name = meta.getColumnName(i); try { /* * 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:io.fineo.drill.rule.TestDrill.java
@Test public void testReadWrite() throws Exception { // writer a simple json file Map<String, Object> json = new HashMap<>(); json.put("a", "c"); File tmp = folder.newFolder("drill"); File out = new File(tmp, "test.json"); JSON j = JSON.std;/*from w w w .j av a 2 s. c o m*/ j.write(json, out); try (Connection conn = drill.getConnection()) { conn.createStatement().execute("ALTER SESSION SET `store.format`='json'"); String select = String.format("SELECT * FROM dfs.`%s`", out.getPath()); ResultSet results = conn.createStatement().executeQuery(select); assertTrue(results.next()); assertEquals(json.get("a"), results.getString("a")); assertEquals(1, results.getMetaData().getColumnCount()); } }