List of usage examples for java.sql ResultSet getInt
int getInt(String columnLabel) throws SQLException;
ResultSet
object as an int
in the Java programming language. From source file:com.tfm.utad.sqoopdata.SqoopVerticaDB.java
private static void findBetweenMinIDAndMaxID(Connection conn, Long minID, Long maxID) { Statement stmt = null;//www .jav a2 s . c o m String query; try { stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); query = "SELECT * FROM s1.coordinates WHERE id > " + minID + " AND id <= " + maxID + ""; LOG.info("Query execution: " + query); ResultSet rs = stmt.executeQuery(query); int batch = 0; List<CoordinateCartoDB> result = new ArrayList<>(); long start_time = System.currentTimeMillis(); while (rs.next()) { batch++; CoordinateCartoDB cdb = new CoordinateCartoDB((long) rs.getInt("id"), rs.getString("userstr"), rs.getString("created_date"), rs.getString("activity"), rs.getFloat("latitude"), rs.getFloat("longitude"), (long) rs.getInt("userid")); result.add(cdb); if (batch == 50) { sendDataToCartoDB(result); batch = 0; result = new ArrayList<>(); } } if (batch > 0) { sendDataToCartoDB(result); } long end_time = System.currentTimeMillis(); long difference = end_time - start_time; LOG.info("CartoDB API execution time: " + String.format("%d min %d sec", TimeUnit.MILLISECONDS.toMinutes(difference), TimeUnit.MILLISECONDS.toSeconds(difference) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(difference)))); } catch (SQLException e) { LOG.error("SQLException error: " + e.toString()); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { LOG.error("Statement error: " + ex.toString()); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { LOG.error("Connection error: " + ex.toString()); } } } }
From source file:module.entities.NameFinder.DB.java
public static ArrayList<Integer> getConsultationIds() throws SQLException { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM consultation;"); ArrayList<Integer> ids = new ArrayList<>(); while (rs.next()) { ids.add(rs.getInt(1)); }/*from ww w. j a v a 2 s .c om*/ return ids; }
From source file:agendavital.modelo.data.Noticia.java
public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro) throws ConexionBDIncorrecta, SQLException { final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro); TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null; try (Connection conexion = ConfigBD.conectar()) { busqueda = new TreeMap<>(); for (String _tag : _tags) { String tag = ConfigBD.String2Sql(_tag, true); String buscar = String.format("SELECT id_Noticia, fecha from noticias " + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas " + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) " + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s " + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag); ResultSet rs = conexion.createStatement().executeQuery(buscar); while (rs.next()) { LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter); Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia")); if (busqueda.containsKey(date)) { boolean encontrado = false; for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++) if (busqueda.get(date).get(i).getId() == insertarNoticia.getId()) encontrado = true; if (!encontrado) busqueda.get(date).add(insertarNoticia); } else { busqueda.put(date, new ArrayList<>()); busqueda.get(date).add(insertarNoticia); }/*from w ww . jav a 2 s.c o m*/ } } } catch (SQLException e) { e.printStackTrace(); } Iterator it = busqueda.keySet().iterator(); return busqueda; }
From source file:com.concursive.connect.web.modules.setup.utils.SetupUtils.java
/** * Determines if the database schema has been created * * @param db// w ww . j av a 2s . c o m * @return */ public static boolean isDatabaseInstalled(Connection db) { int count = -1; try { Statement st = db.createStatement(); ResultSet rs = st.executeQuery("SELECT count(*) AS recordcount " + "FROM database_version "); rs.next(); count = rs.getInt("recordcount"); rs.close(); st.close(); } catch (Exception e) { } return count > 0; }
From source file:org.zenoss.zep.dao.impl.DaoUtils.java
/** * Returns a map of column names to their JDBC type in the specified table. The map is returned in the order * returned by the getColumns query./* w w w.j ava 2 s .co m*/ * * @param dataSource DataSource to use. * @param tableName Table name. * @return A map of column names to the column types in the specified table. * @throws MetaDataAccessException If an exception occurs. */ public static Map<String, Integer> getColumnNamesAndTypes(final DataSource dataSource, final String tableName) throws MetaDataAccessException { final Map<String, Integer> columnNamesToTypes = new LinkedHashMap<String, Integer>(); JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() { @Override public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException { ResultSet rs = dbmd.getColumns(null, null, tableName, null); while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); int columnType = rs.getInt("DATA_TYPE"); columnNamesToTypes.put(columnName, columnType); } rs.close(); return null; } }); return columnNamesToTypes; }
From source file:com.chaosinmotion.securechat.server.commands.GetMessages.java
public static ReturnResult processRequest(Login.UserInfo userinfo, JSONObject requestParams) throws ClassNotFoundException, SQLException, IOException { String deviceid = requestParams.optString("deviceid"); MessageReturnResult mrr = new MessageReturnResult(); /*/*from www.ja v a2 s.c om*/ * Save message to the database. */ Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try { /* * Get the device ID for this device. Verify it belongs to the * user specified */ c = Database.get(); ps = c.prepareStatement("SELECT deviceid " + "FROM Devices " + "WHERE deviceuuid = ? AND userid = ?"); ps.setString(1, deviceid); ps.setInt(2, userinfo.getUserID()); rs = ps.executeQuery(); int deviceID = 0; if (rs.next()) { deviceID = rs.getInt(1); } rs.close(); ps.close(); if (deviceID == 0) { return new ReturnResult(Errors.ERROR_UNKNOWNDEVICE, "Unknown device"); } /* * Run query to get messages */ ps = c.prepareStatement("SELECT Messages.messageid, " + " Messages.senderid, " + " Users.username, " + " Messages.toflag, " + " Messages.received, " + " Messages.message " + "FROM Messages, Users " + "WHERE Messages.deviceid = ? " + " AND Messages.senderid = Users.userid"); ps.setInt(1, deviceID); rs = ps.executeQuery(); while (rs.next()) { int messageID = rs.getInt(1); int senderID = rs.getInt(2); String senderName = rs.getString(3); boolean toflag = rs.getBoolean(4); Timestamp received = rs.getTimestamp(5); byte[] message = rs.getBytes(6); mrr.addMessage(messageID, senderID, senderName, toflag, received, message); } /* * Return messages */ return mrr; } finally { if (rs != null) rs.close(); if (ps != null) ps.close(); if (c != null) c.close(); } }
From source file:de.unibremen.informatik.tdki.combo.ui.CommandComplete.java
private static void dropFilter(String namePattern) { // TODO: add a stored procedure for filter dropping try {/* www . j a va 2 s .com*/ final QueryRunner qRunner = new QueryRunner(); qRunner.query( "SELECT funcname, parm_count FROM Syscat.Functions WHERE funcname LIKE '" + namePattern + "%'", new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { StringBuilder query = new StringBuilder(); query.append("DROP FUNCTION ").append(rs.getString(1)).append("("); int noOfParams = rs.getInt(2); for (int i = 0; i < noOfParams; i++) { query.append("INTEGER"); if (i != noOfParams - 1) { query.append(","); } } query.append(")"); qRunner.update(connection, query.toString()); } }); } catch (SQLException ex) { throw new RuntimeException(ex); } }
From source file:bizlogic.Records.java
public static void add(Connection DBcon, String sensor_name, String smpl_interval, String running, String name) throws SQLException { String isRunning;/*from ww w.j a va 2 s .c o m*/ Statement st; ResultSet rs = null; try { st = DBcon.createStatement(); rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST WHERE NAME = '" + sensor_name + "' "); } catch (SQLException ex) { Logger lgr = Logger.getLogger(Records.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } rs.next(); int id = rs.getInt("sensor_id"); String sql_statement; if (running.equals("true")) { isRunning = "B'1'"; } else { isRunning = "B'0'"; } st = DBcon.createStatement(); sql_statement = "INSERT INTO USERCONF.LOG_LIST(SENSOR_ID, SMPL_INTERVAL, RUNNING, NAME) " + "VALUES (" + id + ", " + smpl_interval + ", " + isRunning + ", " + "'" + name + "'" + " );"; System.out.println(sql_statement); st.clearBatch(); st = DBcon.createStatement(); DBcon.createStatement(); st.executeUpdate(sql_statement); }
From source file:controler.DbModules.java
public static int findCustomerId(String EmailAddress) { String usql = "SELECT cust_id FROM customer WHERE email_adress=\"" + EmailAddress + "\""; Connection conn = DbModules.getConnection(); int id = 0;/*from w ww. j av a 2 s. co m*/ try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(usql); if (rs.next()) { id = rs.getInt("cust_id"); } } catch (SQLException e) { e.printStackTrace(); } return id; }
From source file:com.flexive.core.LifeCycleInfoImpl.java
/** * Helper function for a less error prone and faster loading from the database * * @param rs ResultSet containing all the required info * @param creatorColumn column index of the create user reference * @param creationTimeColumn column index of the create timestamp * @param modificatorColumns column index of the modified by user reference * @param modificationTimeColumn column index of the modified by timestamp * @return LifeCycleInfo with the relevant data gathered from the ResultSet * @throws java.sql.SQLException if a column could not be read *//* ww w . java2s . c om*/ public static LifeCycleInfo load(ResultSet rs, int creatorColumn, int creationTimeColumn, int modificatorColumns, int modificationTimeColumn) throws SQLException { if (rs == null) { throw new IllegalArgumentException("Can not read from a null ResultSet!"); } int cid; long ct; int mid; long mt; long dTmp; cid = rs.getInt(creatorColumn); if (rs.wasNull()) { cid = NOT_DEFINED; } dTmp = rs.getLong(creationTimeColumn); ct = (rs.wasNull() ? NOT_DEFINED : dTmp); if (modificatorColumns < 0) { mid = NOT_DEFINED; } else { mid = rs.getInt(modificatorColumns); if (rs.wasNull()) mid = NOT_DEFINED; } if (modificationTimeColumn < 0) { mt = NOT_DEFINED; } else { dTmp = rs.getLong(modificationTimeColumn); mt = (rs.wasNull() ? NOT_DEFINED : dTmp); } return new LifeCycleInfoImpl(cid, ct, mid, mt); }