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:dept_integration.Dept_Integbean.java
public static int getPages(Connection con) throws Exception { int totalcount = 0; PreparedStatement ps = null;/*from w w w.j a v a2 s . c o m*/ ResultSet rs = null; try { String sql = "select ceil(count(*)/10) as totalpage from department_integration"; ps = con.prepareStatement(sql); rs = ps.executeQuery(); if (rs.next()) { totalcount = rs.getInt("totalpage"); } } catch (Exception e) { System.out.println(e.getMessage()); } return totalcount; }
From source file:au.org.ala.sds.GeneraliseOccurrenceLocations.java
private static void run(String startAt) throws SQLException, SearchResultException { Connection conn = occurrenceDataSource.getConnection(); PreparedStatement pst = conn.prepareStatement( "SELECT id, scientific_name, latitude, longitude, generalised_metres, raw_latitude, raw_longitude FROM raw_occurrence_record LIMIT ?,?"); int offset = startAt == null ? 0 : Integer.parseInt(startAt); int stride = 10000; int recCount = 0; pst.setInt(2, stride);/*from ww w. ja v a 2 s.co m*/ ResultSet rs; for (pst.setInt(1, offset); true; offset += stride, pst.setInt(1, offset)) { rs = pst.executeQuery(); if (!rs.isBeforeFirst()) { break; } while (rs.next()) { recCount++; String rawScientificName = (rs.getString("scientific_name")); int id = rs.getInt("id"); String latitude = rs.getString("latitude"); String longitude = rs.getString("longitude"); String generalised_metres = rs.getString("generalised_metres"); String raw_latitude = rs.getString("raw_latitude"); String raw_longitude = rs.getString("raw_longitude"); if (StringUtils.isEmpty(rawScientificName)) continue; if (StringUtils.isEmpty(latitude) || StringUtils.isEmpty(longitude)) continue; // See if it's sensitive SensitiveTaxon ss = sensitiveSpeciesFinder.findSensitiveSpecies(rawScientificName); if (ss != null) { Map<String, String> facts = new HashMap<String, String>(); facts.put(FactCollection.DECIMAL_LATITUDE_KEY, latitude); facts.put(FactCollection.DECIMAL_LONGITUDE_KEY, longitude); ValidationService service = ServiceFactory.createValidationService(ss); ValidationOutcome outcome = service.validate(facts); Map<String, Object> result = outcome.getResult(); String speciesName = ss.getTaxonName(); if (StringUtils.isNotEmpty(ss.getCommonName())) { speciesName += " [" + ss.getCommonName() + "]"; } if (!result.get("decimalLatitude").equals(facts.get("decimalLatitude")) || !result.get("decimalLongitude").equals(facts.get("decimalLongitude"))) { if (StringUtils.isEmpty(generalised_metres)) { logger.info("Generalising location for " + id + " '" + rawScientificName + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude") + ", Long=" + result.get("decimalLongitude")); //rawOccurrenceDao.updateLocation(id, result.get("decimalLatitude"), result.get("decimalLongitude"), result.getGeneralisationInMetres(), latitude, longitude); } else { if (generalised_metres != result.get("generalisationInMetres")) { logger.info("Re-generalising location for " + id + " '" + rawScientificName + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude") + ", Long=" + result.get("decimalLongitude")); //rawOccurrenceDao.updateLocation(id, result.get("decimalLatitude"), result.get("decimalLongitude"), result.getGeneralisationInMetres()); } } } else { logger.info("Not generalising location for " + id + " '" + rawScientificName + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude") + ", Long=" + result.get("decimalLongitude") + " - " + result.get("dataGeneralizations")); } } else { // See if was sensitive but not now if (StringUtils.isNotEmpty(generalised_metres)) { logger.info("De-generalising location for " + id + " '" + rawScientificName + "', Lat=" + raw_latitude + ", Long=" + raw_longitude); //rawOccurrenceDao.updateLocation(id, raw_latitude, raw_longitude, null, null, null); } } } rs.close(); logger.info("Processed " + recCount + " occurrence records."); } rs.close(); pst.close(); conn.close(); }
From source file:net.sf.webphotos.tools.Thumbnail.java
/** * Abre uma conexo com o banco de dados atravs da classe BancoImagem, * busca um lote de imagens e faz thumbs para todas as fotos. No possui * utilizaes./*from w ww . j ava 2s .c o m*/ */ public static void executaLote() { net.sf.webphotos.BancoImagem db = net.sf.webphotos.BancoImagem.getBancoImagem(); try { db.configure("jdbc:mysql://localhost/test", "com.mysql.jdbc.Driver"); BancoImagem.login(); java.sql.Connection conn = BancoImagem.getConnection(); java.sql.Statement st = conn.createStatement(); java.sql.ResultSet rs = st.executeQuery("select * from fotos"); int albumID, fotoID; String caminho; while (rs.next()) { albumID = rs.getInt("albumID"); fotoID = rs.getInt("fotoID"); caminho = "d:/bancoImagem/" + albumID + "/" + fotoID + ".jpg"; makeThumbs(caminho); Util.out.println(caminho); } rs.close(); st.close(); conn.close(); } catch (Exception e) { e.printStackTrace(Util.err); } }
From source file:agendavital.modelo.data.Noticia.java
/** * Funcion que inserta la noticia en la BD * * @param titulo//from ww w.ja v a 2s.co m * @param link * @param fecha * @param categoria * @param cuerpo * @param tags * @return * @throws agendavital.modelo.excepciones.ConexionBDIncorrecta * @throws java.sql.SQLException */ public static Noticia Insert(String titulo, String link, String fecha, String categoria, String cuerpo, ArrayList<String> tags) throws ConexionBDIncorrecta, SQLException { int nuevoId = 0; try (Connection conexion = ConfigBD.conectar()) { String insert = "INSERT INTO noticias (titulo, link, fecha, categoria, cuerpo)"; insert += String.format(" VALUES (%s, %s, %s, %s, %s)", ConfigBD.String2Sql(titulo, false), ConfigBD.String2Sql(link, false), ConfigBD.String2Sql((fecha), false), ConfigBD.String2Sql(categoria, false), ConfigBD.String2Sql(cuerpo, false)); int executeUpdate = conexion.createStatement().executeUpdate(insert); nuevoId = ConfigBD.LastId("noticias"); for (String tag : tags) { String consultaTag = String.format("SELECT id_etiqueta from etiquetas WHERE Nombre = %s;", ConfigBD.String2Sql(tag, false)); ResultSet rs = conexion.createStatement().executeQuery(consultaTag); rs.next(); int idTag = (rs.getRow() == 1) ? rs.getInt("id_etiqueta") : -1; if (idTag == -1) { String insertTag = String.format("INSERT INTO etiquetas (nombre) VALUES (%s);", ConfigBD.String2Sql(tag, false)); conexion.createStatement().executeUpdate(insertTag); idTag = ConfigBD.LastId("etiquetas"); } String insertNoticiaEtiqueta = String.format( "INSERT INTO momentos_noticias_etiquetas (id_noticia, id_etiqueta) VALUES(%d, %d);", nuevoId, idTag); conexion.createStatement().executeUpdate(insertNoticiaEtiqueta); } } catch (SQLException e) { } return new Noticia(nuevoId); }
From source file:com.oracle.tutorial.jdbc.CoffeesTable.java
public static void alternateViewTable(Connection con) throws SQLException { Statement stmt = null;/* w ww.ja va 2 s. com*/ String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString(1); int supplierID = rs.getInt(2); float price = rs.getFloat(3); int sales = rs.getInt(4); int total = rs.getInt(5); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmt != null) { stmt.close(); } } }
From source file:com.seventh_root.ld33.common.player.Player.java
public static Player getByUUID(Connection databaseConnection, UUID uuid) throws SQLException { if (playersByUUID.containsKey(uuid.toString())) return playersByUUID.get(uuid.toString()); if (databaseConnection != null) { PreparedStatement statement = databaseConnection.prepareStatement( "SELECT uuid, name, password_hash, password_salt, resources FROM player WHERE uuid = ? LIMIT 1"); statement.setString(1, uuid.toString()); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { Player player = new Player(databaseConnection, UUID.fromString(resultSet.getString("uuid")), resultSet.getString("name"), resultSet.getString("password_hash"), resultSet.getString("password_salt"), resultSet.getInt("resources")); cachePlayer(player);// w w w. jav a 2s .c om return player; } } return null; }
From source file:com.concursive.connect.web.webdav.WebdavManager.java
public static int validateUser(Connection db, HttpServletRequest req) throws Exception { String argHeader = req.getHeader("Authorization"); HashMap params = getAuthenticationParams(argHeader); String username = (String) params.get("username"); if (md5Helper == null) { md5Helper = MessageDigest.getInstance("MD5"); }//from w w w.jav a 2 s . c o m int userId = -1; String password = null; PreparedStatement pst = db.prepareStatement( "SELECT user_id, webdav_password " + "FROM users " + "WHERE username = ? " + "AND enabled = ? "); pst.setString(1, username); pst.setBoolean(2, true); ResultSet rs = pst.executeQuery(); if (rs.next()) { userId = rs.getInt("user_id"); password = rs.getString("webdav_password"); } rs.close(); pst.close(); if (userId == -1) { return userId; } String method = req.getMethod(); String uri = (String) params.get("uri"); String a2 = MD5Encoder.encode(md5Helper.digest((method + ":" + uri).getBytes())); String digest = MD5Encoder .encode(md5Helper.digest((password + ":" + params.get("nonce") + ":" + a2).getBytes())); if (!digest.equals(params.get("response"))) { userId = -1; } return userId; }
From source file:las.DBConnector.java
public static ArrayList<Item> getItemTable() throws SQLException { ArrayList<Item> table = new ArrayList<>(); String data = "SELECT * FROM Items"; PreparedStatement pt = conn.prepareStatement(data); ResultSet rs = pt.executeQuery(); while (rs.next()) { table.add(new Item(rs.getString("title"), rs.getString("author"), rs.getString("type"), rs.getInt("Item_ID"), rs.getInt("amountleft"))); }//from www.jav a 2 s .co m return table; }
From source file:com.oracle.tutorial.jdbc.CoffeesTable.java
public static void viewTable(Connection con) throws SQLException { Statement stmt = null;/* w ww .j a v a 2s . co m*/ String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmt != null) { stmt.close(); } } }
From source file:jp.co.acroquest.endosnipe.data.dao.AbstractDao.java
/** * ????<br />/*from ww w . jav a 2 s . c om*/ * * @param database ?? * @param table ?? * @param notNullKey NULL ??? * @return ? * @throws SQLException SQL ????? */ protected static int count(final String database, final String table, final String notNullKey) throws SQLException { int count = 0; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConnection(database, true); String sql = "select count(" + notNullKey + ") from " + table; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs.next() == true) { count = rs.getInt(1); } } finally { SQLUtil.closeResultSet(rs); SQLUtil.closeStatement(stmt); SQLUtil.closeConnection(conn); } return count; }