List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:com.groupon.odo.proxylib.SQLService.java
/** * Gets the first row for a query//from ww w . j a v a 2s.c o m * * @param query * @return result or NULL */ public HashMap<String, Object> getFirstResult(String query) throws Exception { HashMap<String, Object> result = null; Statement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = getConnection()) { queryStatement = sqlConnection.createStatement(); results = queryStatement.executeQuery(query); if (results.next()) { result = new HashMap<String, Object>(); String[] columns = getColumnNames(results.getMetaData()); for (String column : columns) { result.put(column, results.getObject(column)); } } } catch (Exception e) { } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return result; }
From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java
@SuppressWarnings("unchecked") @Override//from w w w. j av a2 s . com public T mapRow(ResultSet r, int index) throws SQLException { try { T obj = (T) clazz.newInstance(); if (obj == null) { return null; } try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { Object value = null; try { Method setter = property.getWriteMethod(); value = r.getObject(key.toLowerCase()); if (value != null && value instanceof Number) { @SuppressWarnings("rawtypes") Class[] types = setter.getParameterTypes(); value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]); } if (value != null) { if (value.getClass().equals(BigInteger.class)) { setter.invoke(obj, ((BigInteger) value).longValue()); } else if (value.getClass().equals(byte[].class)) { setter.invoke(obj, new String((byte[]) value)); } else if (Blob.class.isAssignableFrom(value.getClass())) { Blob bv = (Blob) value; byte[] b = new byte[(int) bv.length()]; InputStream stream = bv.getBinaryStream(); stream.read(b); stream.close(); String v = new String(b); setter.invoke(obj, v); } else { setter.invoke(obj, value); } } } catch (Exception e) { logger.error("transBean2Map Error " + e); logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString()) + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:" + e.getMessage()); } } } } catch (Exception e) { logger.error("transBean2Map Error " + e); } return obj; } catch (Exception e) { logger.error("Exception:" + e); } return null; }
From source file:Formulario.CapturaHuella.java
public void guardarHuella(String nom) { String rut = jTextField1.getText(); if (rut.isEmpty()) { EnviarTexto("No se ha ingresado el rut del usuario"); } else {//ww w . java2 s . c o m try { Connection c = cn.conectar(); PreparedStatement buscar = c.prepareStatement( "select count(*) numero from municipalidad.foto_contribuyente where rut = ?"); String rut_form = Metodos_Rut.formatear(nom); buscar.setString(1, rut_form); ResultSet rs = buscar.executeQuery(); if (rs.next()) { Object numero = rs.getObject("numero"); int resultado = Integer.parseInt(numero.toString()); if (resultado == 0) { System.out.println("tienes que insertar"); PreparedStatement insertar = c.prepareStatement( "INSERT INTO municipalidad.foto_contribuyente(rut,pulgar_der) values(?,?)"); insertar.setString(1, rut_form); insertar.setBinaryStream(2, fis, longitudBytes); insertar.execute(); insertar.close(); JOptionPane.showMessageDialog(null, "Huella Guardada Correctamente"); } else { PreparedStatement guardarStmt = c.prepareStatement( " update municipalidad.foto_contribuyente set pulgar_der = ? where rut= ?"); guardarStmt.setBinaryStream(1, fis, longitudBytes); guardarStmt.setString(2, nom); //Ejecuta la sentencia guardarStmt.execute(); guardarStmt.close(); JOptionPane.showMessageDialog(null, "Huella Guardada Correctamente"); } } //SQL AQUI //PreparedStatement guardarStmt = c.prepareStatement("INSERT INTO somhue(huenombre, huehuella) values(?,?)");//AQUI SQL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //AQUI // PreparedStatement guardarStmt = c.prepareStatement("INSERT INTO municipalidad.foto_contribuyente(pulgar_der) values(?) WHERE rut=?"); // cn.desconectar(); btnGuardar.setEnabled(false); } catch (SQLException ex) { //Si ocurre un error lo indica en la consola System.err.println("Error al guardar los datos de la huella."); } finally { cn.desconectar(); } } }
From source file:net.fender.sql.ManagedConnectionDataSource.java
/** * Tests if managedConnection != null, wrappedConnection != null && * !isClosed(), then runs validation query. Closes the connection on * SQLException.//from w ww. j a v a2s . com * * @param managedConnection * @throws InvalidConnectionException */ protected void validateConnection(ManagedConnection managedConnection) throws InvalidConnectionException { if (managedConnection == null) { throw new InvalidConnectionException("managedConnection is null"); } // only validate the base connection if (managedConnection.isValid()) { return; } managedConnection.setValid(false); Connection connection = managedConnection.getConnection(); if (connection == null) { throw new InvalidConnectionException("wrapped connection is null"); } Statement statement = null; ResultSet resultSet = null; try { if (connection.isClosed()) { throw new InvalidConnectionException("wrapped connection is closed"); } // if no validation query, then assume it is ok if (StringUtils.isBlank(validationQuery)) { managedConnection.setValid(true); return; } statement = connection.createStatement(); resultSet = statement.executeQuery(validationQuery); if (resultSet.next()) { log.debug("connection validation returned " + resultSet.getObject(1)); managedConnection.setValid(true); } } catch (SQLException e) { JdbcUtils.close(connection); throw new InvalidConnectionException(e); } finally { JdbcUtils.close(resultSet, statement); } }
From source file:com.smhdemo.common.report.generate.factory.ChartFactory.java
/** * ?//from w w w . ja v a 2s . c om * * @param reportDataSet ?? * @param sql SQL? * @return DefaultCategoryDataset * @throws BaseException */ @SuppressWarnings("rawtypes") private DefaultCategoryDataset buildDataset(Chart report, Map<String, String> pageParams) throws BaseException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Connection con = null; DataSourceServiceable service = null; int colCount; try { Base dataSet = report.getBaseDS(); String executableSQL = report.getChartSql(); executableSQL = replaceParam(pageParams, report.getParameters(), executableSQL, true); if (dataSet == null) { con = dataSource.getConnection(); } else { DataSourceFactoryable factory = (DataSourceFactoryable) initDataSourceFactory .getBean(dataSet.getClass()); service = factory.createService(dataSet); con = service.openConnection(); } Statement st = con.createStatement(); ResultSet rs = st.executeQuery(executableSQL); colCount = rs.getMetaData().getColumnCount(); if (colCount == 2) { while (rs.next()) { try { try { dataset.addValue(rs.getDouble(1), "", (Comparable) rs.getObject(2)); } catch (Exception e) { dataset.addValue(rs.getDouble(2), "", (Comparable) rs.getObject(1)); } } catch (Exception e) { logger.error("SQL?", e); throw new BaseException("SQL?", "SQL?"); } } } else if (colCount == 3) { while (rs.next()) { try { try { dataset.addValue(rs.getDouble(3), (Comparable) rs.getObject(1), (Comparable) rs.getObject(2)); } catch (Exception e) { try { dataset.addValue(rs.getDouble(2), (Comparable) rs.getObject(1), (Comparable) rs.getObject(3)); } catch (Exception ex) { dataset.addValue(rs.getDouble(1), (Comparable) rs.getObject(2), (Comparable) rs.getObject(3)); } } } catch (Exception e) { logger.error("SQL?", e); throw new BaseException("SQL?", "SQL?"); } } } else { logger.error("SQL??12"); throw new BaseException("?12", "?12"); } st.close(); rs.close(); } catch (Exception e) { throw new BaseException(e.toString(), e.toString()); } finally { if (service != null) { service.closeConnection(); } if (con != null) { try { con.close(); } catch (SQLException e) { } con = null; } } return dataset; }
From source file:org.tradex.jdbc.JDBCHelper.java
/** * Executes the passed SQL and returns the results in a 2D object array * @param sql The SQL query to executer//w ww .j a v a2s .co m * @return the results of the query */ public Object[][] query(CharSequence sql) { Connection conn = null; PreparedStatement ps = null; ResultSet rset = null; Vector<Object[]> rows = new Vector<Object[]>(); try { conn = ds.getConnection(); ps = conn.prepareStatement(sql.toString()); rset = ps.executeQuery(); int colCount = rset.getMetaData().getColumnCount(); while (rset.next()) { Object[] row = new Object[colCount]; for (int i = 1; i <= colCount; i++) { row[i - 1] = rset.getObject(i); } rows.add(row); } Object[][] result = new Object[rows.size()][]; int cnt = 0; for (Object[] row : rows) { result[cnt] = row; cnt++; } return result; } catch (Exception e) { throw new RuntimeException("Query for [" + sql + "] failed", e); } finally { try { rset.close(); } catch (Exception e) { } try { ps.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
From source file:it.unibas.spicy.persistence.idgenerator.utils.ReadDB.java
public ArrayList<InputDataModel> readSourceDatabase(ArrayList<ColumnMatcherModel> cmmList) throws SQLException, IOException, ClassNotFoundException { ArrayList<InputDataModel> inputData = new ArrayList<>(); ArrayList<String> configurationProperties = getExportDatabaseConfig(); Connection connection = null; try {/*www .jav a2s . c o m*/ connection = getConnectionToDatabase(configurationProperties.get(0), configurationProperties.get(1) + configurationProperties.get(4), configurationProperties.get(2), configurationProperties.get(3)); Statement statement = connection.createStatement(); String columnsToQuery = ""; for (ColumnMatcherModel cmm : cmmList) { if (!cmm.getSourceColumn().equalsIgnoreCase("CONSTANT_VALUE_SOURCE")) { columnsToQuery += cmm.getSourceColumn() + ","; } } ResultSet tableRows = null; if (columnsToQuery.length() > 0) { columnsToQuery = columnsToQuery.substring(0, columnsToQuery.length() - 1); tableRows = statement.executeQuery("SELECT " + columnsToQuery + " FROM " + table + ";"); } else { tableRows = statement.executeQuery("SELECT * FROM " + table + ";"); } ResultSetMetaData rsmd = tableRows.getMetaData(); int columnsNumber = rsmd.getColumnCount(); while (tableRows.next()) { InputDataModel idm = new InputDataModel(); for (int i = 1; i <= columnsNumber; i++) { idm.addValue(String.valueOf(tableRows.getObject(i))); if (columnsToQuery.length() > 0) { idm.addKey(columnsToQuery.split(",")[i - 1]); } else { idm.addKey("none"); } } inputData.add(idm); } } catch (ClassNotFoundException | SQLException e) { System.err.println(e.getMessage()); System.exit(-1); } finally { if (connection != null) connection.close(); } return inputData; }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public List<Map<String, Object>> dumpResultSetToList(ResultSet rs) throws SQLException { List<Map<String, Object>> rsml = new ArrayList<>(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { Map<String, Object> d = new LinkedHashMap<>(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { d.put(rsmd.getColumnLabel(col), rs.getObject(col)); }/*from w ww . ja va 2 s.c o m*/ rsml.add(d); } LOG.trace("{} rows loaded", rsml.size()); return rsml; }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testUUID() throws SQLException { Statement stat = conn.createStatement(); stat.execute("create table test_uuid(id uuid primary key)"); UUID uuid = new UUID(-2, -1); PreparedStatement prep = conn.prepareStatement("insert into test_uuid values(?)"); prep.setObject(1, uuid);/*from w ww .ja va 2 s .c om*/ prep.execute(); ResultSet rs = stat.executeQuery("select * from test_uuid"); rs.next(); assertEquals("ffffffff-ffff-fffe-ffff-ffffffffffff", rs.getString(1)); Object o = rs.getObject(1); assertEquals("java.util.UUID", o.getClass().getName()); stat.execute("drop table test_uuid"); }
From source file:com.glaf.core.web.springmvc.MxSystemDbTableController.java
@ResponseBody @RequestMapping("/json") public byte[] json(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); JSONArray rowsJSON = new JSONArray(); String[] types = { "TABLE" }; Connection connection = null; try {//from w w w . j a va 2 s .c o m connection = DBConnectionFactory.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); ResultSet rs = metaData.getTables(null, null, null, types); int startIndex = 1; while (rs.next()) { String tableName = rs.getObject("TABLE_NAME").toString(); if (!DBUtils.isAllowedTable(tableName)) { continue; } if (tableName.toLowerCase().startsWith("cell_useradd")) { continue; } if (tableName.toLowerCase().startsWith("sys_data_log")) { continue; } if (tableName.toLowerCase().startsWith("temp")) { continue; } if (tableName.toLowerCase().startsWith("tmp")) { continue; } if (DBUtils.isTemoraryTable(tableName)) { continue; } JSONObject json = new JSONObject(); json.put("startIndex", startIndex++); json.put("cat", rs.getObject("TABLE_CAT")); json.put("schem", rs.getObject("TABLE_SCHEM")); json.put("tablename", tableName); json.put("tableName_enc", RequestUtils.encodeString(tableName)); rowsJSON.add(json); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(connection); } result.put("rows", rowsJSON); result.put("total", rowsJSON.size()); return result.toJSONString().getBytes("UTF-8"); }