List of usage examples for java.sql ResultSetMetaData getColumnLabel
String getColumnLabel(int column) throws SQLException;
From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java
public List<DBColumn> getColumns(String schema, String table) throws NextSqlException, MalformedTableNameException { Connection con;/*from w ww .j a v a 2s .c o m*/ List<DBColumn> columns = new ArrayList<DBColumn>(); String schemaName; String escapedTableName; try { con = Globals.getConnection(); if (schema == null) { schemaName = Globals.getConnection().getMetaData().getUserName(); } else { schemaName = schema; } Dialect dialect = Globals.getDialect(); if (dialect.isKeyWord(table)) { escapedTableName = dialect.getEscapedKeyWord(table); } else { escapedTableName = table; } } catch (Exception e) { throw new NextSqlException("Could not retrieve connection.", e); } ResultSet rs = null; Statement stmt = null; List<String> keyColumns = new ArrayList<String>(); try { // primary keys DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getPrimaryKeys(null, schemaName, table); while (rs.next()) { keyColumns.add(rs.getString("COLUMN_NAME")); } closeResultSet(rs); // foreign keys rs = dbmd.getImportedKeys(null, schemaName, table); List<String> foreignColumns = new ArrayList<String>(); HashMap<String, DBForeignColumnInfo> fkMap = new HashMap<String, DBForeignColumnInfo>(); while (rs.next()) { String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String fkColumn = rs.getString("FKCOLUMN_NAME"); String pkSchema = rs.getString("PKTABLE_SCHEM"); String pkTable = rs.getString("PKTABLE_NAME"); String pkColumn = rs.getString("PKCOLUMN_NAME"); DBForeignColumnInfo fkInfo = new DBForeignColumnInfo(fkSchema, fkTable, fkColumn, pkSchema, pkTable, pkColumn); //System.out.println("fkInfo : " + fkInfo); foreignColumns.add(fkColumn); fkMap.put(fkColumn, fkInfo); } closeResultSet(rs); // column names with index rs = dbmd.getIndexInfo(null, schemaName, table, false, true); List<String> indexes = new ArrayList<String>(); while (rs.next()) { String indexName = rs.getString(9); if (indexName != null) { indexes.add(indexName); } } closeResultSet(rs); DataSource ds = DefaultDataSourceManager.getInstance().getConnectedDataSource(); String header = ""; stmt = con.createStatement(); try { // workaround if a table name contains spaces if (escapedTableName.indexOf(" ") != -1) { escapedTableName = "\"" + escapedTableName + "\""; } String prefix = ""; if (!NO_SCHEMA_NAME.equals(schemaName)) { prefix = schemaName; } if (prefix.indexOf(" ") != -1) { prefix = "\"" + prefix + "\""; } if (!"".equals(prefix)) { prefix = prefix + "."; } if (ds.getDriver().equals(CSVDialect.DRIVER_CLASS)) { header = (String) ds.getProperties().get("headerline"); if (header == null) { header = ""; } } if (header.isEmpty()) { String s = "SELECT * FROM " + prefix + escapedTableName + " WHERE 1 = 0"; LOG.info("getColumns[ " + s + "]"); rs = stmt.executeQuery(s); } } catch (SQLException e) { e.printStackTrace(); throw new MalformedTableNameException(e); } if (header.isEmpty()) { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int col = 1; col <= columnCount; col++) { String name = rsmd.getColumnLabel(col); int length = rsmd.getColumnDisplaySize(col); int precision = rsmd.getPrecision(col); int scale = rsmd.getScale(col); boolean isPrimaryKey = false; boolean isForeignKey = false; boolean isIndex = false; if (keyColumns.contains(name)) { isPrimaryKey = true; } DBForeignColumnInfo fkInfo = null; if (foreignColumns.contains(name)) { isForeignKey = true; fkInfo = fkMap.get(name); } if (indexes.contains(name)) { isIndex = true; } DBColumn column = new DBColumn(schemaName, table, name, rsmd.getColumnTypeName(col), isPrimaryKey, isForeignKey, isIndex, fkInfo, length, precision, scale); columns.add(column); } } else { String columnTypes = (String) ds.getProperties().get("columnTypes"); String[] names = header.split(","); String[] types = new String[names.length]; for (int i = 0; i < types.length; i++) { types[i] = "String"; } if ((columnTypes != null) && !columnTypes.isEmpty()) { types = columnTypes.split(","); } for (int i = 0; i < names.length; i++) { DBColumn column = new DBColumn(schemaName, table, names[i], types[i], false, false, false, null, 20, 0, 0); columns.add(column); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(rs); closeStatement(stmt); } return columns; }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Get column names for a query statement that we do not modify further. *//* w w w .j a v a 2 s. c om*/ public String[] getColumnNamesForRawQuery(String stmt) { ResultSet results; try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString(), sqlE); release(); return null; } try { int cols = results.getMetaData().getColumnCount(); ArrayList<String> columns = new ArrayList<String>(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); if (null == colName) { colName = "_RESULT_" + i; } } columns.add(colName); } return columns.toArray(new String[0]); } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString(), sqlException); return null; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString(), sqlE); } release(); } }
From source file:com.iih5.smartorm.model.Model.java
/** * Model/*from w w w .java 2s .com*/ * * @param columns ?? columns="id,name,age" * @param conditions ? conditions="user_id=? and age=?" * @param conditionParas ?? * @param <T> * @return Model * @ */ <T> List<T> queryList(String columns, String conditions, Object[] conditionParas) { String sql = DefaultDialect.getDialect().forModelFindBy(table, columns, conditions); final Set<String> columnMeta = new HashSet<String>(); return jdbc.query(sql, conditionParas, new RowMapper<T>() { public T mapRow(ResultSet rs, int rowNum) throws SQLException { try { if (columnMeta.size() == 0) { for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { String column = rs.getMetaData().getColumnLabel(i + 1); columnMeta.add(column); } } Model<?> mModel = getUsefulClass().newInstance(); Field[] fields = mModel.getClass().getFields(); if (fields.length > 0) { for (Field f : fields) { if (columnMeta.contains(f.getName())) { f.set(mModel, rs.getObject(f.getName())); } } } else { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Map<String, Object> attrs = mModel.getAttrs(); for (int i = 1; i <= columnCount; i++) { Object value = rs.getObject(i); if (value != null) { attrs.put(rsmd.getColumnLabel(i), value); } } } return (T) mModel; } catch (Exception e) { e.printStackTrace(); } return null; } }); }
From source file:controlador.Peticiones.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www. j a va 2s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); String target, op, action, view; target = request.getParameter("target"); op = request.getParameter("op"); if (target.equals("login")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String login = request.getParameter("login"); String pass = request.getParameter("password"); ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='" + Auxiliar.encriptarPass(pass) + "'"); JSONObject objetoJSON = new JSONObject(); response.setContentType("application/json; charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { if (r != null && r.next()) { objetoJSON.put("r", "1"); out.print(objetoJSON); } else { objetoJSON.put("r", "0"); out.print(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } } else { if (target.equals("pedido")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String s = request.getParameter("datos"); JSONTokener token = new JSONTokener(s); JSONArray ar = null; ArrayList<Producto> productos = new ArrayList(); try { ar = new JSONArray(token); for (int i = 0; i < ar.length(); i++) { agregarProducto(ar.getJSONObject(i).getInt("idMesa"), ar.getJSONObject(i).getInt("idProducto")); ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = " + ar.getJSONObject(i).getInt("idProducto")); rs.next(); String nombre = rs.getString("nombreProducto"); Producto pr = new Producto(nombre); if (productos.contains(pr)) { int pos = productos.indexOf(pr); productos.get(pos).sumaCantidad(); } else { productos.add(new Producto(nombre)); } } ResultSet nombreMesa = bd.ejecutarSelect( "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa=" + ar.getJSONObject(0).getInt("idMesa")); nombreMesa.next(); String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona"); Comanda comanda = new Comanda(productos, nombre); System.out.println("Ticket: \n" + comanda.contenidoComanda); Auxiliar.imprimir(comanda.contenidoComanda); } catch (JSONException ex) { System.out.println("Error JSON " + ex.toString()); } catch (SQLException ex) { System.out.println("Error SQL " + ex.toString()); } // Crear un el objeto para enviar a comanda para imprimir, implementar response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); try { obj.put("r", "recibido"); } catch (JSONException ex) { } out.print(obj); out.flush(); } else { if (target.equals("mesas")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("familias")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { ; } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("productos")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } } } } } }
From source file:org.openanzo.jdbc.container.query.AnzoSolutionGeneratorBase.java
/** * //www. jav a 2 s . c o m * We need to translate this result set into our own bindings. This means: 1) converting column names to Bindable objects 2) ignoring the fake unit column * 3) mapping back from Anzo IDs to BNode Nodes to Glitter objects 4) associating the appropriate openrdf object with the bindable key * */ protected int addBindings(AnzoBGPQuery query, TreeNode node, ResultSet rs, SolutionSet bindings, String glitterIgnoredVariable, Connection connection, QueryController controller) throws SQLException, AnzoException { int resultsProcessed = 0; try { ResultSetMetaData meta = rs.getMetaData(); // HashMap<Integer, Bindable> columns = new HashMap<Integer, Bindable>(); int lastColumn = meta.getColumnCount(); Bindable columns[] = new Bindable[lastColumn + 1]; for (int i = 1; i <= lastColumn; i++) { String name = meta.getColumnLabel(i); if (!name.equals(glitterIgnoredVariable)) { // 2) columns[i] = query.getBindableForAlias(name); // 1) } } // TODO we'd like to filter here if possible, but it breaks if we're inside a LeftJoin that has // filters... while (rs.next()) { if (controller.isCancelled()) { throw new GlitterException(ExceptionConstants.GLITTER.QUERY_CANCELLED); } resultsProcessed++; PatternSolutionImpl solution = new PatternSolutionImpl(); for (int j = 1; j < columns.length; j++) { if (columns[j] != null) { long id = rs.getLong(j); if (id != 0) { org.openanzo.rdf.Value value = this.nodeConverter.getGlitterNode(id, connection); // 3) solution.setBinding(columns[j], value); } } } bindings.add(solution); } this.nodeConverter.resolveNodes(connection); } finally { if (rs != null) { rs.close(); } } return resultsProcessed; }
From source file:org.apache.wink.rest.ClockinResource.java
@Path(PATH_DATABASE) @GET//from w w w . j a va2 s.c o m @Produces(MediaType.APPLICATION_JSON) public Response getData(@QueryParam("table") String table) { Status status = Response.Status.OK; JsonObject dataTable = new JsonObject(); Connection con = null; String result = null; try { //connect to database via connection pool DatabaseConnectionPool dbpool = DatabaseConnectionPool.getInstance(); con = dbpool.getConnection(); //create the statement object Statement stmt = con.createStatement(); //prevent sql injection String sqlStatement = null; try { System.out.println("table: " + table); DATABASE_TABLES.valueOf(table.toLowerCase()); sqlStatement = "select * from " + table; } catch (IllegalArgumentException e) { throw new Exception("Table does not exist in the database."); } //step execute query ResultSet rs = stmt.executeQuery(sqlStatement); ResultSetMetaData rsmd = rs.getMetaData(); int rsmdLength = rsmd.getColumnCount(); dataTable.addProperty("columnCount", rsmdLength); JsonArray jaColumns = new JsonArray(); for (int i = 0; i < rsmdLength; i++) { jaColumns.add(rsmd.getColumnLabel(i + 1)); } dataTable.add("columns", jaColumns); int rowCount = 0; JsonArray array = new JsonArray(); while (rs.next()) { rowCount++; JsonArray ja = new JsonArray(); for (int i = 0; i < rsmdLength; i++) { ja.add(rs.getString(i + 1)); } array.add(ja); } dataTable.add("rows", array); dataTable.addProperty("rowCount", rowCount); System.out.println("dataTable.toString() " + dataTable.toString()); result = dataTable.toString(); } catch (Exception e) { System.out.println("Catching exception: " + e.getMessage()); status = Response.Status.INTERNAL_SERVER_ERROR; result = e.getMessage(); } finally { //step5 close the connection object try { con.close(); } catch (Exception e) { System.out.println("Finally: " + e.getMessage()); } } return Response.status(status).entity(result).header("Content-Type", "application/json").build(); }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Get column types for a query statement that we do not modify further. *///from w w w .j av a 2s . c o m protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) { ResultSet results; try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString()); release(); return null; } try { Map<String, Integer> colTypes = new HashMap<String, Integer>(); int cols = results.getMetaData().getColumnCount(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { int typeId = metadata.getColumnType(i); String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); } colTypes.put(colName, Integer.valueOf(typeId)); } return colTypes; } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString()); return null; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString()); } release(); } }
From source file:rapture.repo.jdbc.JDBCStructuredStore.java
protected Boolean refreshColumnTypeCache(final String tableName) { return jdbc.query(sqlGenerator.constructSelect(schema, tableName, null, "1=0", null, null, -1), new ResultSetExtractor<Boolean>() { @Override// w w w .j a v a2 s . c o m public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException { ResultSetMetaData rsmd = rs.getMetaData(); Map<String, Integer> columnType = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (int i = 1; i <= rsmd.getColumnCount(); i++) { columnType.put(rsmd.getColumnLabel(i), rsmd.getColumnType(i)); } cache.putColumnTypes(tableName, columnType); return true; } }); }
From source file:org.openiot.gsn.storage.StorageManager.java
public DataField[] tableToStructure(CharSequence tableName, Connection connection) throws SQLException { StringBuilder sb = new StringBuilder("select * from ").append(tableName).append(" where 1=0 "); ResultSet rs = null;//from w ww . j a v a 2s.co m DataField[] toReturn = null; try { rs = executeQueryWithResultSet(sb, connection); ResultSetMetaData structure = rs.getMetaData(); ArrayList<DataField> toReturnArr = new ArrayList<DataField>(); for (int i = 1; i <= structure.getColumnCount(); i++) { String colName = structure.getColumnLabel(i); if (colName.equalsIgnoreCase("pk")) continue; int colType = structure.getColumnType(i); byte colTypeInGSN = convertLocalTypeToGSN(colType); toReturnArr.add(new DataField(colName, colTypeInGSN)); } toReturn = toReturnArr.toArray(new DataField[] {}); } finally { if (rs != null) close(rs); } return toReturn; }
From source file:org.openiot.gsn.storage.StorageManager.java
public DataField[] tableToStructureByString(String tableName, Connection connection) throws SQLException { StringBuilder sb = new StringBuilder("select * from ").append(tableName).append(" where 1=0 "); ResultSet rs = null;// ww w. j a va 2s . c o m DataField[] toReturn = null; try { rs = executeQueryWithResultSet(sb, connection); ResultSetMetaData structure = rs.getMetaData(); ArrayList<DataField> toReturnArr = new ArrayList<DataField>(); for (int i = 1; i <= structure.getColumnCount(); i++) { String colName = structure.getColumnLabel(i); if (colName.equalsIgnoreCase("pk")) continue; if (colName.equalsIgnoreCase("timed")) continue; int colType = structure.getColumnType(i); String colTypeName = structure.getColumnTypeName(i); int precision = structure.getPrecision(i); byte colTypeInGSN = convertLocalTypeToGSN(colType); if ((colTypeInGSN == DataTypes.VARCHAR) || (colTypeInGSN == DataTypes.CHAR)) toReturnArr.add(new DataField(colName, colTypeName, precision, colName)); else toReturnArr.add(new DataField(colName, colTypeInGSN)); } toReturn = toReturnArr.toArray(new DataField[] {}); } finally { if (rs != null) close(rs); } return toReturn; }