List of usage examples for java.sql ResultSet getString
String getString(String columnLabel) throws SQLException;
ResultSet
object as a String
in the Java programming language. From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getOracleConnection(); Statement stmt = null;/* w w w. j a va2 s . co m*/ ResultSet rs = null; stmt = conn.createStatement(); //only for Oracle rs = stmt.executeQuery("select object_name from user_objects where object_type = 'VIEW'"); while (rs.next()) { String tableName = rs.getString(1); System.out.println("viewName=" + tableName); } stmt.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sqlQuery = "SELECT uid, name, duration from EVENTS"; ResultSet rs = stmt.executeQuery(sqlQuery); while (rs.next()) { rs.updateString("Name", "new Name"); rs.updateRow();// w ww. j a v a2 s .co m } rs.first(); while (rs.next()) { String name = rs.getString(2); Timestamp hireDate = rs.getTimestamp(5); System.out.println("Name: " + name + " Hire Date: " + hireDate); } rs.close(); }
From source file:ImageStringToBlob.java
public static void main(String[] args) { Connection conn = null;//w ww .jav a 2 s. c o m if (args.length != 1) { System.out.println("Missing argument: full path to <oscar.properties>"); return; } try { FileInputStream fin = new FileInputStream(args[0]); Properties prop = new Properties(); prop.load(fin); String driver = prop.getProperty("db_driver"); String uri = prop.getProperty("db_uri"); String db = prop.getProperty("db_name"); String username = prop.getProperty("db_username"); String password = prop.getProperty("db_password"); Class.forName(driver); conn = DriverManager.getConnection(uri + db, username, password); conn.setAutoCommit(true); // no transactions /* * select all records ids with image_data not null and contents is null * for each id fetch record * migrate data from image_data to contents */ String sql = "select image_id from client_image where image_data is not null and contents is null"; PreparedStatement pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); List<Long> ids = new ArrayList<Long>(); while (rs.next()) { ids.add(rs.getLong("image_id")); } rs.close(); sql = "select image_data from client_image where image_id = ?"; pst = conn.prepareStatement(sql); System.out.println("Migrating image data for " + ids.size() + " images..."); for (Long id : ids) { pst.setLong(1, id); ResultSet imagesRS = pst.executeQuery(); while (imagesRS.next()) { String dataString = imagesRS.getString("image_data"); Blob dataBlob = fromStringToBlob(dataString); if (writeBlobToDb(conn, id, dataBlob) == 1) { System.out.println("Image data migrated for image_id: " + id); } } imagesRS.close(); } System.out.println("Migration completed."); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,null)"); st.executeUpdate("insert into survey (id,name ) values (3,'Tom')"); ResultSet rs = st.executeQuery("SELECT * FROM survey"); // Move cursor to the end, after the last row rs.afterLast();/*from w w w .j a v a2 s .c o m*/ //String id = rs.getString("id");//Exception rs.previous(); // Get data at cursor String id = rs.getString("id"); System.out.println(id); rs.close(); st.close(); conn.close(); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java JavaDBDemo <Name> <Address>"); System.exit(1);//ww w. j a va 2 s . c om } String driver = "org.apache.derby.jdbc.EmbeddedDriver"; String dbName = "AddressBookDB"; String connectionURL = "jdbc:derby:" + dbName + ";create=true"; String createString = "CREATE TABLE ADDRESSBOOKTbl (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)"; Class.forName(driver); conn = DriverManager.getConnection(connectionURL); Statement stmt = conn.createStatement(); stmt.executeUpdate(createString); PreparedStatement psInsert = conn.prepareStatement("insert into ADDRESSBOOKTbl values (?,?)"); psInsert.setString(1, args[0]); psInsert.setString(2, args[1]); psInsert.executeUpdate(); Statement stmt2 = conn.createStatement(); ResultSet rs = stmt2.executeQuery("select * from ADDRESSBOOKTbl"); System.out.println("Addressed present in your Address Book\n\n"); int num = 0; while (rs.next()) { System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2)); } rs.close(); }
From source file:geocodingsql.Main.java
/** * @param args the command line arguments *//* ww w .j a v a2 s .c o m*/ public static void main(String[] args) throws JSONException { Main x = new Main(); ResultSet rs = null; String string = ""; x.establishConnection(); rs = x.giveName(); try { while (rs.next()) { string += rs.getString(1) + " "; } JOptionPane.showMessageDialog(null, string, "authors", 1); } catch (Exception e) { System.out.println("Problem when printing the database."); } x.closeConnection(); // Now do Geocoding String req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=41.3166662867211,-72.9062497615814&result_type=point_of_interest&key=" + key; try { URL url = new URL(req + "&sensor=false"); URLConnection conn = url.openConnection(); ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copy(conn.getInputStream(), output); output.close(); req = output.toString(); } catch (Exception e) { System.out.println("Geocoding Error"); } JSONObject jObject = new JSONObject(req); JSONArray resultArray = jObject.getJSONArray("results"); //this prints out the neighborhood of the provided coordinates System.out.println(resultArray.getJSONObject(0).getJSONArray("address_components") .getJSONObject("neighborhood").getString("long_name")); }
From source file:BatchUpdate.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;// w w w .java2 s . c om 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:GetDBInfo.java
public static void main(String[] args) { Connection c = null; // The JDBC connection to the database server try {/*from w ww. j ava2s .c o m*/ // Look for the properties file DB.props in the same directory as // this program. It will contain default values for the various // parameters needed to connect to a database Properties p = new Properties(); try { p.load(GetDBInfo.class.getResourceAsStream("DB.props")); } catch (Exception e) { } // Get default values from the properties file String driver = p.getProperty("driver"); // Driver class name String server = p.getProperty("server", ""); // JDBC URL for server String user = p.getProperty("user", ""); // db user name String password = p.getProperty("password", ""); // db password // These variables don't have defaults String database = null; // The db name (appended to server URL) String table = null; // The optional name of a table in the db // Parse the command-line args to override the default values above for (int i = 0; i < args.length; i++) { if (args[i].equals("-d")) driver = args[++i]; //-d <driver> else if (args[i].equals("-s")) server = args[++i];//-s <server> else if (args[i].equals("-u")) user = args[++i]; //-u <user> else if (args[i].equals("-p")) password = args[++i]; else if (database == null) database = args[i]; // <dbname> else if (table == null) table = args[i]; // <table> else throw new IllegalArgumentException("Unknown argument: " + args[i]); } // Make sure that at least a server or a database were specified. // If not, we have no idea what to connect to, and cannot continue. if ((server.length() == 0) && (database.length() == 0)) throw new IllegalArgumentException("No database specified."); // Load the db driver, if any was specified. if (driver != null) Class.forName(driver); // Now attempt to open a connection to the specified database on // the specified server, using the specified name and password c = DriverManager.getConnection(server + database, user, password); // Get the DatabaseMetaData object for the connection. This is the // object that will return us all the data we're interested in here DatabaseMetaData md = c.getMetaData(); // Display information about the server, the driver, etc. System.out.println("DBMS: " + md.getDatabaseProductName() + " " + md.getDatabaseProductVersion()); System.out.println("JDBC Driver: " + md.getDriverName() + " " + md.getDriverVersion()); System.out.println("Database: " + md.getURL()); System.out.println("User: " + md.getUserName()); // Now, if the user did not specify a table, then display a list of // all tables defined in the named database. Note that tables are // returned in a ResultSet, just like query results are. if (table == null) { System.out.println("Tables:"); ResultSet r = md.getTables("", "", "%", null); while (r.next()) System.out.println("\t" + r.getString(3)); } // Otherwise, list all columns of the specified table. // Again, information about the columns is returned in a ResultSet else { System.out.println("Columns of " + table + ": "); ResultSet r = md.getColumns("", "", table, "%"); while (r.next()) System.out.println("\t" + r.getString(4) + " : " + r.getString(6)); } } // Print an error message if anything goes wrong. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println(((SQLException) e).getSQLState()); System.err.println("Usage: java GetDBInfo [-d <driver] " + "[-s <dbserver>]\n" + "\t[-u <username>] [-p <password>] <dbname>"); } // Always remember to close the Connection object when we're done! finally { try { c.close(); } catch (Exception e) { } } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,null)"); st.executeUpdate("insert into survey (id,name ) values (3,'Tom')"); ResultSet rs = st.executeQuery("SELECT * FROM survey"); rs.last();/*from www. j av a2 s . c om*/ // Move cursor up 2 rows from the current row. If this moves // cursor beyond the first row, cursor is put before the first row rs.relative(-2); // Get data at cursor String id = rs.getString("id"); System.out.println(id); rs.close(); st.close(); conn.close(); }
From source file:TestAccessExcel.java
public static void main(String args[]) { Connection conn = null;//ww w . ja v a 2 s. c om Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(); String excelQuery = "select * from [Sheet1$]"; rs = stmt.executeQuery(excelQuery); while (rs.next()) { System.out.println(rs.getString("BadgeNumber") + " " + rs.getString("FirstName") + " " + rs.getString("LastName")); } } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }