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:InsertSuppliers.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;//from w w w .j av a 2 s .c o m Statement stmt; String query = "select SUP_NAME, SUP_ID from SUPPLIERS"; 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(); stmt.executeUpdate("insert into SUPPLIERS " + "values(49, 'Superior Coffee', '1 Party Place', " + "'Mendocino', 'CA', '95460')"); stmt.executeUpdate("insert into SUPPLIERS " + "values(101, 'Acme, Inc.', '99 Market Street', " + "'Groundsville', 'CA', '95199')"); stmt.executeUpdate("insert into SUPPLIERS " + "values(150, 'The High Ground', '100 Coffee Lane', " + "'Meadows', 'CA', '93966')"); ResultSet rs = stmt.executeQuery(query); System.out.println("Suppliers and their ID Numbers:"); while (rs.next()) { String s = rs.getString("SUP_NAME"); int n = rs.getInt("SUP_ID"); System.out.println(s + " " + n); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:com.sapienter.jbilling.tools.ConvertToBinHexa.java
/** * @param args/*from w w w.j ava 2 s . c o m*/ */ public static void main(String[] args) { String driver = null; if (args.length < 3) { System.err.println("Usage: url username password [driver]"); System.exit(1); return; } if (args.length < 4) { driver = "org.postgresql.Driver"; } else { driver = args[3]; } System.out.println("Converting credit cards ... "); int count = 0; try { connection = getConnection(args[0], args[1], args[2], driver); ResultSet rows = getCCRowsToUpdate(); while (rows == null) { //rows.next() - skip CC int rowId = rows.getInt(1); String cryptedNumber = rows.getString(2); String cryptedName = rows.getString(3); int userId = rows.getInt(4); JBCrypto oldCrypt = JBCrypto.getCreditCardCrypto(); oldCrypt.setUseHexForBinary(false); String plainNumber; try { plainNumber = oldCrypt.decrypt(cryptedNumber); } catch (Exception e) { plainNumber = "Not available"; System.out.println("User id " + userId + " cc id " + rowId + " with bad cc number"); } String plainName; try { plainName = oldCrypt.decrypt(cryptedName); } catch (RuntimeException e) { plainName = "Not available"; System.out.println("User id " + userId + " cc id " + rowId + " with bad cc name"); } // now recrypt using the new way JBCrypto newCrypt = JBCrypto.getCreditCardCrypto(); newCrypt.setUseHexForBinary(true); cryptedName = newCrypt.encrypt(plainName); cryptedNumber = newCrypt.encrypt(plainNumber); //System.out.println("new " + cryptedName + " and " + cryptedNumber); updateCCRow(rowId, cryptedName, cryptedNumber); count++; } rows.close(); System.out.println("Converting user passwords ... "); count = 0; rows = getUserRowsToUpdate(); while (rows.next()) { int rowId = rows.getInt(1); String oldPassword = rows.getString(2); try { String newPassword = Util.binaryToString(Base64.decodeBase64(oldPassword.getBytes())); System.out.println("new " + newPassword + " old " + oldPassword); updateUserRow(rowId, newPassword); count++; } catch (Exception e) { System.out.println("Error with password " + oldPassword + " :" + e.getMessage()); } } rows.close(); connection.close(); } catch (Exception e) { System.err.println("Error! " + e.getMessage()); e.printStackTrace(); System.exit(2); } System.out.println("Finished! " + count + " rows populated"); }
From source file:BatchUpdate.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;//from w ww .ja va 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_UPDATABLE); con.setAutoCommit(false); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); int[] updateCounts = stmt.executeBatch(); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("SQLException: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:ResultSetExample.java
public static void main(String args[]) { try {// www. j a v a 2 s . co m Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:Inventory", "", ""); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT SupplierName,ProductName, Price " + "FROM ProductSuppliersView WHERE CategoryName LIKE '%BEVERAGES%' "); while (rs.next()) { String supplier = rs.getString("SupplierName"); String product = rs.getString("ProductName"); int price = rs.getInt("Price"); System.out.println(supplier + " sells " + product + " for $" + price); } stmt.close(); con.close(); } catch (Exception e) { System.out.println(e); } }
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')"); DatabaseMetaData meta = conn.getMetaData(); // The '_' character represents any single character. // The '%' character represents any sequence of zero // or more characters. ResultSet rs = meta.getBestRowIdentifier(conn.getCatalog(), null, "survey", DatabaseMetaData.bestRowTemporary, false); while (rs.next()) { short actualScope = rs.getShort("SCOPE"); String columnName = rs.getString("COLUMN_NAME"); int dataType = rs.getInt("DATA_TYPE"); String typeName = rs.getString("TYPE_NAME"); int columnSize = rs.getInt("COLUMN_SIZE"); short decimalDigits = rs.getShort("DECIMAL_DIGITS"); short pseudoColumn = rs.getShort("PSEUDO_COLUMN"); System.out.println("tableName=survey"); System.out.println("scope=" + actualScope); System.out.println("columnName=" + columnName); System.out.println("dataType=" + dataType); System.out.println("typeName" + typeName); System.out.println("columnSize" + columnSize); System.out.println("decimalDigits" + decimalDigits); System.out.println("pseudoColumn" + pseudoColumn); }//from ww w .ja v a2 s .c om st.close(); conn.close(); }
From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java
public static void main(String[] args) { long start = System.currentTimeMillis(); String fid = null;// w ww . ja v a 2s . co m logger.info( "args[0] = threadcount, args[1] = db connection string, args[2] = db username, args[3] = password"); if (args.length >= 4) { CONCURRENT_THREADS = Integer.parseInt(args[0]); db_url = args[1]; db_usr = args[2]; db_pwd = args[3]; } if (args.length > 4) { fid = args[4]; } Connection c = getConnection(); //String count_sql = "select count(*) as cnt from objects where bbox is null or area_km is null"; String count_sql = "select count(*) as cnt from objects where area_km is null and st_geometrytype(the_geom) <> 'ST_Point' "; if (StringUtils.isEmpty(fid)) { count_sql = count_sql + " and fid = '" + fid + "'"; } int count = 0; try { Statement s = c.createStatement(); ResultSet rs = s.executeQuery(count_sql); while (rs.next()) { count = rs.getInt("cnt"); } } catch (Exception e) { logger.error(e.getMessage(), e); } int iter = count / 200000; logger.info("Breaking into " + iter + " iterations"); for (int i = 0; i <= iter; i++) { long iterStart = System.currentTimeMillis(); // updateBbox(); updateArea(fid); logger.info("iteration " + i + " completed after " + (System.currentTimeMillis() - iterStart) + "ms"); logger.info("total time taken is " + (System.currentTimeMillis() - start) + "ms"); } }
From source file:JDBCQuery.java
public static void main(String[] av) { try {/*from ww w .j a v a2 s . c o m*/ System.out.println("Loading Driver (with Class.forName)"); // Load the jdbc-odbc bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Enable logging // DriverManager.setLogStream(System.err); System.out.println("Getting Connection"); Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd // Any warnings generated by the connect? checkForWarning(conn.getWarnings()); System.out.println("Creating Statement"); Statement stmt = conn.createStatement(); System.out.println("Executing Query"); ResultSet rs = stmt.executeQuery("SELECT * FROM Companies"); System.out.println("Retrieving Results"); int i = 0; while (rs.next()) { System.out.println("Retrieving Company ID"); int x = rs.getInt("CustNO"); System.out.println("Retrieving Name"); String s = rs.getString("Company"); System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + "."); } rs.close(); // All done with that resultset stmt.close(); // All done with that statement conn.close(); // All done with that DB connection } catch (ClassNotFoundException e) { System.out.println("Can't load driver " + e); } catch (SQLException e) { System.out.println("Database access failed " + e); } }
From source file:TypeInfo.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w w w. j av a2 s. com*/ DatabaseMetaData dbmd; 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"); dbmd = con.getMetaData(); ResultSet rs = dbmd.getTypeInfo(); while (rs.next()) { String typeName = rs.getString("TYPE_NAME"); short dataType = rs.getShort("DATA_TYPE"); String createParams = rs.getString("CREATE_PARAMS"); int nullable = rs.getInt("NULLABLE"); boolean caseSensitive = rs.getBoolean("CASE_SENSITIVE"); System.out.println("DBMS type " + typeName + ":"); System.out.println(" java.sql.Types: " + dataType); System.out.print(" parameters used to create: "); System.out.println(createParams); System.out.println(" nullable?: " + nullable); System.out.print(" case sensitive?: "); System.out.println(caseSensitive); System.out.println(""); } con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:ex4.java
public static void main(String[] params) { CommandLine commandLine = null;/*from w w w.ja v a 2 s . com*/ String sqlpath = "", host = "", port = "3306", username = "", password = "", database = ""; Boolean query = false; Option option_sql = Option.builder("s").argName("sql").hasArg() .desc("Path to a file containing a valid MySQL sql statement").build(); Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname") .build(); Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build(); Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username") .build(); Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password") .build(); Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name") .build(); Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build(); Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build(); Options options = new Options(); CommandLineParser parser = new DefaultParser(); options.addOption(option_sql); options.addOption(option_hostname); options.addOption(option_port); options.addOption(option_username); options.addOption(option_password); options.addOption(option_dbname); options.addOption(option_query); options.addOption(option_help); try { commandLine = parser.parse(options, params); } catch (MissingOptionException e) { help(options); } catch (MissingArgumentException e) { help(options); } catch (ParseException e) { System.out.println(e); } if (commandLine.hasOption("w") || params.length == 0) { help(options); } if (commandLine.hasOption("s")) { sqlpath = commandLine.getOptionValue("s"); } else { System.out.println("Missing path to a SQL statement file"); help(options); } if (commandLine.hasOption("h")) { host = commandLine.getOptionValue("h"); } else { System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)"); help(options); } if (commandLine.hasOption("n")) { port = commandLine.getOptionValue("n"); } else { System.out.println("Missing ClearDB Port Value. Defaulting to 3306"); } if (commandLine.hasOption("u")) { username = commandLine.getOptionValue("u"); } else { System.out.println("Missing ClearDB Username"); help(options); } if (commandLine.hasOption("p")) { password = commandLine.getOptionValue("p"); } else { System.out.println("Missing ClearDB Password"); help(options); } if (commandLine.hasOption("d")) { database = commandLine.getOptionValue("d"); } else { System.out.println("Missing ClearDB Database Name"); help(options); } if (commandLine.hasOption("query")) { query = true; } String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port) .append("/").append(database).append("?reconnect=true").toString(); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println(e); } try { Connection con = DriverManager.getConnection(connectionURL, username, password); Statement stmt = con.createStatement(); if (query) { System.out.println("Querying target MySQL DB ..."); ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset())); while (rs.next()) System.out.println(rs.getInt("emp_no") + " " + rs.getDate("birth_date") + " " + rs.getString("first_name") + " " + rs.getString("last_name") + " " + rs.getString("gender") + " " + rs.getDate("hire_date")); } else { System.out.println("Updating target MySQL DB ..."); int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset())); System.out.println(result); } con.close(); } catch (Exception e) { System.out.println(e); } }
From source file:CountRecordsUsingPreparedStatement.java
public static void main(String[] args) { ResultSet rs = null; Connection conn = null;/*from ww w. java2 s. c om*/ PreparedStatement pstmt = null; try { conn = getConnection(); String query = "select count(*) from tableName"; pstmt = conn.prepareStatement(query); rs = pstmt.executeQuery(); if (rs.next()) { int numberOfRows = rs.getInt(1); System.out.println("numberOfRows= " + numberOfRows); } else { System.out.println("error: could not get the record counts"); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }