List of usage examples for java.sql ResultSet next
boolean next() throws SQLException;
From source file:TestClassForNameNewInstanceApp.java
public static void main(String args[]) { try {/* ww w .j a v a2 s .com*/ Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch (ClassNotFoundException e) { System.out.println("Oops! Can't find class oracle.jdbc.driver.OracleDriver"); System.exit(1); } catch (IllegalAccessException e) { System.out.println("Uh Oh! You can't load oracle.jdbc.driver.OracleDriver"); System.exit(2); } catch (InstantiationException e) { System.out.println("Geez! Can't instantiate oracle.jdbc.driver.OracleDriver"); System.exit(3); } Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = DriverManager.getConnection("jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger"); stmt = conn.createStatement(); rset = stmt.executeQuery("select 'Hello '||USER||'!' result from dual"); while (rset.next()) System.out.println(rset.getString(1)); rset.close(); rset = null; stmt.close(); stmt = null; conn.close(); conn = null; } catch (SQLException e) { System.out.println("Darn! A SQL error: " + e.getMessage()); } finally { if (rset != null) try { rset.close(); } catch (SQLException ignore) { } if (stmt != null) try { stmt.close(); } catch (SQLException ignore) { } if (conn != null) try { conn.close(); } catch (SQLException ignore) { } } }
From source file:com.alifi.jgenerator.spring.SpringGeneratorFactory.java
public static void main(String[] args) { @SuppressWarnings("unused") ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/SpringContext.xml"); for (DataSourceMap m : DataSourceUtil.getDataSourceMap()) { DataSource ds = m.getDataSource(); try {//from ww w .j ava2 s. c o m Connection con = ds.getConnection(); DatabaseMetaData dmd = con.getMetaData(); String catalog = con.getCatalog(); String schemaPattern = dmd.getSchemaTerm(); System.out.println("Catalog:" + con.getCatalog() + " schemaPattern:" + schemaPattern); ResultSet rs = dmd.getTables(catalog, schemaPattern, "time_zone_transition", null); Statement s = null; ResultSet xrs = null; try { s = con.createStatement(); xrs = s.executeQuery("select * from time_zone_transition"); if (xrs.next()) { p("xxxxxxxxxxxxxxxxxxxxxxxx:" + xrs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { } while (rs.next()) { p("-----------------------"); p("TABLE_CAT :" + rs.getString("TABLE_CAT")); p("TABLE_SCHEM:" + rs.getString("TABLE_SCHEM")); p("TABLE_NAME :" + rs.getString("TABLE_NAME")); p("TABLE_TYPE :" + rs.getString("TABLE_TYPE")); p("REMARKS: " + rs.getString("REMARKS")); p("11111111111111111:" + rs.getMetaData().getColumnClassName(1)); // ResultSet pkeyRs = dmd.getPrimaryKeys(catalog, schemaPattern, rs.getString("TABLE_NAME")); while (pkeyRs.next()) { p("M-------------M"); p("------COLUMN_NAME:" + pkeyRs.getString("COLUMN_NAME")); p("------KEY_SEQ:" + pkeyRs.getString("KEY_SEQ")); p("------PK_NAME:" + pkeyRs.getString("PK_NAME")); } // ResultSet rss = dmd.getColumns(catalog, schemaPattern, rs.getString("TABLE_NAME"), null); int cCount = rss.getMetaData().getColumnCount(); for (int i = 1; i <= cCount; i++) { p("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); p(" getColumnClassName:" + rss.getMetaData().getColumnClassName(i)); p(" getColumnLabel:" + rss.getMetaData().getColumnLabel(i)); p(" getColumnName:" + rss.getMetaData().getColumnName(i)); p(" getColumnTypeName:" + rss.getMetaData().getColumnTypeName(i)); p(" getColumnType:" + ColumnTypes.getType(rss.getMetaData().getColumnType(i))); } } rs = dmd.getTableTypes(); while (rs.next()) { p("========================="); p("TABLE_TYPE: " + rs.getString("TABLE_TYPE")); } // ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); // for (int i = 1; i <= numberOfColumns; i++) // p(rsmd.getColumnName(i)); } catch (SQLException e) { e.printStackTrace(); } p(m.toString()); } }
From source file:fr.eo.util.dumper.JSONDumper.java
/** * @param args main args//from www. j ava 2 s . c om */ public static void main(String[] args) { String appName = args[0]; String jdbcConnectionType = args.length > 1 ? args[1] : "jtds"; System.out.println("Starting dumper ..."); try (Connection conn = getConnection(jdbcConnectionType)) { System.out.println("Getting database connection ..."); List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName); baseFolder = RequestDefinitionParser.getAppBaseDir(appName) + "/"; System.out.println("Reading old table dumps..."); Map<String, JsonTableDump> oldTables = JSONDeltaDumper.readOldTables(baseFolder); List<JsonTableDump> newTables = new ArrayList<>(); for (RequestDefinitionBean request : requests) { try (Statement stmt = conn.createStatement()) { BufferedWriter bw = getWriter(request.name, baseFolder); if (!request.disabled) { System.out.println("Dumping " + request.name + "..."); ResultSet rs = stmt.executeQuery(request.sql); JsonTableWritable dump = new JsonTableWritable(); dump.name = request.table; while (rs.next()) { int pos = 0; for (String fieldName : request.fields) { Object obj = getFieldValue(request, pos, rs, fieldName); dump.addColumn(obj); pos++; } dump.commit(); } bw.append(dump.toJson()); newTables.add(dump); bw.flush(); bw.close(); } else { System.out.println("Skiping " + request.name + "..."); } } System.out.println("done."); } newTables.addAll(BlueprintDumper.dump(baseFolder)); newTables.addAll(TranslationsDumper.dump(baseFolder, jdbcConnectionType)); System.out.println("Computing delta..."); JSONDeltaDumper.computeDelta(oldTables, newTables, baseFolder); } catch (SQLException | ClassNotFoundException | IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); DatabaseMetaData mtdt = conn.getMetaData(); // list catalogs managed by this dbms System.out.println(mtdt.getCatalogTerm()); ResultSet rs = mtdt.getCatalogs(); ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount(); for (int i = 1; i <= numCols; i++) { if (i > 1) System.out.print(", "); System.out.print(rsmd.getColumnLabel(i)); }/*from w w w .ja v a 2 s . com*/ System.out.println(""); while (rs.next()) { for (int i = 1; i <= numCols; i++) { if (i > 1) System.out.print(", "); System.out.print(rs.getString(i)); } System.out.println(""); } conn.close(); }
From source file:GetColumnPrivilegesOracle.java
public static void main(String[] args) throws Exception { Connection conn = null;//from ww w . ja va 2 s .c om conn = getConnection(); String catalogPattern = conn.getCatalog(); String schemaPattern = "SYSTEM"; String tableNamePattern = "HELP"; ResultSet privileges = null; DatabaseMetaData meta = conn.getMetaData(); // The '_' character represents any single character. // The '%' character represents any sequence of zero or more characters. privileges = meta.getTablePrivileges(catalogPattern, schemaPattern, tableNamePattern); while (privileges.next()) { String catalog = privileges.getString("TABLE_CAT"); String schema = privileges.getString("TABLE_SCHEM"); String tableName = privileges.getString("TABLE_NAME"); String privilege = privileges.getString("PRIVILEGE"); String grantor = privileges.getString("GRANTOR"); String grantee = privileges.getString("GRANTEE"); String isGrantable = privileges.getString("IS_GRANTABLE"); System.out.println("table name:" + tableName); System.out.println("catalog:" + catalog); System.out.println("schema:" + schema); System.out.println("privilege:" + privilege); System.out.println("grantor:" + grantor); System.out.println("isGrantable:" + isGrantable); System.out.println("grantee:" + grantee); conn.close(); } }
From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer.java
public static void main(String[] args) { connect(HOST, DATABASE, USER, PASSWORD); Map<Integer, String> items = new HashMap<Integer, String>(); Map<Integer, String> failed = new HashMap<Integer, String>(); // fetch coveredTexts of dubious items and clean it PreparedStatement select = null; try {// w w w .j av a 2 s .c om StringBuilder selectQuery = new StringBuilder(); selectQuery.append("SELECT * FROM EvaluationItem "); selectQuery.append("WHERE LOCATE(coveredText, ' ') > 0 "); selectQuery.append("OR LOCATE('" + LRB + "', coveredText) > 0 "); selectQuery.append("OR LOCATE('" + RRB + "', coveredText) > 0 "); selectQuery.append("OR LEFT(coveredText, 1) = ' ' "); selectQuery.append("OR RIGHT(coveredText, 1) = ' ' "); select = connection.prepareStatement(selectQuery.toString()); log.info("Running query [" + selectQuery.toString() + "]."); ResultSet rs = select.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String coveredText = rs.getString("coveredText"); try { // special handling of double whitespace: in this case, re-fetch the text if (coveredText.contains(" ")) { coveredText = retrieveCoveredText(rs.getString("collectionId"), rs.getString("documentId"), rs.getInt("beginOffset"), rs.getInt("endOffset")); } // replace bracket placeholders and trim the text coveredText = StringUtils.replace(coveredText, LRB, "("); coveredText = StringUtils.replace(coveredText, RRB, ")"); coveredText = coveredText.trim(); items.put(id, coveredText); } catch (IllegalArgumentException e) { failed.put(id, e.getMessage()); } } } catch (SQLException e) { log.error("Exception while selecting: " + e.getMessage()); } finally { closeQuietly(select); } // write logs BufferedWriter bwf = null; BufferedWriter bws = null; try { bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(LOG_FAILED)), "UTF-8")); for (Entry<Integer, String> e : failed.entrySet()) { bwf.write(e.getKey() + " - " + e.getValue() + "\n"); } bws = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(LOG_SUCCESSFUL)), "UTF-8")); for (Entry<Integer, String> e : items.entrySet()) { bws.write(e.getKey() + " - " + e.getValue() + "\n"); } } catch (IOException e) { log.error("Got an IOException while writing the log files."); } finally { IOUtils.closeQuietly(bwf); IOUtils.closeQuietly(bws); } log.info("Texts for [" + items.size() + "] items need to be cleaned up."); // update the dubious items with the cleaned coveredText PreparedStatement update = null; try { String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?"; update = connection.prepareStatement(updateQuery); int i = 0; for (Entry<Integer, String> e : items.entrySet()) { int id = e.getKey(); String coveredText = e.getValue(); // update item in database update.setString(1, coveredText); update.setInt(2, id); update.executeUpdate(); log.debug("Updating " + id + " with [" + coveredText + "]"); // show percentage of updated items i++; int part = (int) Math.ceil((double) items.size() / 100); if (i % part == 0) { log.info(i / part + "% finished (" + i + "/" + items.size() + ")."); } } } catch (SQLException e) { log.error("Exception while updating: " + e.getMessage()); } finally { closeQuietly(update); } closeQuietly(connection); }
From source file:DeliverWork.java
public static void main(String[] args) throws UnsupportedEncodingException, MessagingException { JdbcFactory jdbcFactoryChanye = new JdbcFactory( "jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8", "guimin_db", "guimin@98fhi3p2hUFHfdfoi", "com.mysql.jdbc.Driver"); connection = jdbcFactoryChanye.getConnection(); Map<String, String> map = new HashMap(); try {/*w w w .j a v a 2s . c o m*/ PreparedStatement ps = connection.prepareStatement(selectAccount); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { map.put(resultSet.getString(1), resultSet.getString(2)); } ps.close(); map.forEach((k, v) -> { syncTheFile(k, v); }); connection.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:TypeConcurrency.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w ww . java 2 s .co m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT * FROM COFFEES"); int type = srs.getType(); System.out.println("srs is type " + type); int concur = srs.getConcurrency(); System.out.println("srs has concurrency " + concur); while (srs.next()) { String name = srs.getString("COF_NAME"); int id = srs.getInt("SUP_ID"); float price = srs.getFloat("PRICE"); int sales = srs.getInt("SALES"); int total = srs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } srs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getMySqlConnection(); System.out.println("Got Connection."); Statement st = conn.createStatement(); st.executeUpdate("drop table survey;"); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); ResultSet privileges = null; DatabaseMetaData meta = conn.getMetaData(); // The '_' character represents any single character. // The '%' character represents any sequence of zero // or more characters. privileges = meta.getTablePrivileges(conn.getCatalog(), "%", "survey"); while (privileges.next()) { String catalog = privileges.getString("TABLE_CAT"); String schema = privileges.getString("TABLE_SCHEM"); String tableName = privileges.getString("TABLE_NAME"); String privilege = privileges.getString("PRIVILEGE"); String grantor = privileges.getString("GRANTOR"); String grantee = privileges.getString("GRANTEE"); String isGrantable = privileges.getString("IS_GRANTABLE"); System.out.println("table name:" + tableName); System.out.println("catalog:" + catalog); System.out.println("schema:" + schema); System.out.println("privilege:" + privilege); System.out.println("grantor:" + grantor); System.out.println("isGrantable:" + isGrantable); System.out.println("grantee:" + grantee); }// w w w .ja v a2 s .com st.close(); conn.close(); }
From source file:GetNumberOfRowsScrollableResultSet_MySQL.java
public static void main(String[] args) { Connection conn = null;/* w w w . j av a 2 s .c o m*/ Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); String query = "select id from employees"; stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(query); // extract data from the ResultSet scroll from top while (rs.next()) { String id = rs.getString(1); System.out.println("id=" + id); } // move to the end of the result set rs.last(); // get the row number of the last row which is also the row count int rowCount = rs.getRow(); System.out.println("rowCount=" + rowCount); } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }