List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:Main.java
public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String URL = "jdbc:odbc:dbname"; Connection dbConn = DriverManager.getConnection(URL, "user", "passw"); Employee employee = new Employee(42, "AA", 9); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(employee);/*from w w w . ja v a2 s. c o m*/ byte[] employeeAsBytes = baos.toByteArray(); PreparedStatement pstmt = dbConn.prepareStatement("INSERT INTO EMPLOYEE (emp) VALUES(?)"); ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes); pstmt.setBinaryStream(1, bais, employeeAsBytes.length); pstmt.executeUpdate(); pstmt.close(); Statement stmt = dbConn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT emp FROM Employee"); while (rs.next()) { byte[] st = (byte[]) rs.getObject(1); ByteArrayInputStream baip = new ByteArrayInputStream(st); ObjectInputStream ois = new ObjectInputStream(baip); Employee emp = (Employee) ois.readObject(); } stmt.close(); rs.close(); dbConn.close(); }
From source file:MainClass.java
public static void main(String[] args) { try {/* w w w.j a v a 2 s . c o m*/ Class.forName("COM.cloudscape.core.JDBCDriver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:cloudscape:GAMETRADER"); Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM tableName"); while (rs.next()) { int id = rs.getInt("GAMEID"); Document manual = (Document) rs.getObject("MANUAL"); XMLSerializer serialize = new XMLSerializer(System.out, null); serialize.serialize(manual); } } catch (Throwable e) { System.out.println("exception thrown"); System.out.println(e); } }
From source file:Employee.java
public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:ORCL", "yourName", "mypwd"); Statement stmt = conn.createStatement(); Map map = conn.getTypeMap();/*from w w w . j a v a 2s . c o m*/ map.put("EMP_DATA", Class.forName("Employee")); conn.setTypeMap(map); ResultSet rs = stmt.executeQuery("SELECT * from Emp"); Employee employee; while (rs.next()) { int empId = rs.getInt("EmpId"); employee = (Employee) rs.getObject("Emp_Info"); System.out.print("Employee Id: " + empId + ", SSN: " + employee.SSN); System.out.print(", Name: " + employee.FirstName + " " + employee.LastName); System.out.println( ", Yearly Salary: $" + employee.Salary + " Monthly Salary: " + employee.calcMonthlySalary()); } conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getOracleConnection(); String[] columnNames = { "id", "name", "content", "date_created" }; Object[] inputValues = new Object[columnNames.length]; inputValues[0] = new java.math.BigDecimal(100); inputValues[1] = new String("String Value"); inputValues[2] = new String("This is my resume."); inputValues[3] = new Timestamp((new java.util.Date()).getTime()); String insert = "insert into resume (id, name, content, date_created ) values(?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(insert); pstmt.setObject(1, inputValues[0]);/* ww w . j a v a 2 s . c o m*/ pstmt.setObject(2, inputValues[1]); pstmt.setObject(3, inputValues[2]); pstmt.setObject(4, inputValues[3]); pstmt.executeUpdate(); String query = "select id, name, content, date_created from resume where id=?"; PreparedStatement pstmt2 = conn.prepareStatement(query); pstmt2.setObject(1, inputValues[0]); ResultSet rs = pstmt2.executeQuery(); Object[] outputValues = new Object[columnNames.length]; if (rs.next()) { for (int i = 0; i < columnNames.length; i++) { outputValues[i] = rs.getObject(i + 1); } } System.out.println("id=" + ((java.math.BigDecimal) outputValues[0]).toString()); System.out.println("name=" + ((String) outputValues[1])); System.out.println("content=" + ((Clob) outputValues[2])); System.out.println("date_created=" + ((java.sql.Date) outputValues[3]).toString()); rs.close(); pstmt.close(); pstmt2.close(); conn.close(); }
From source file:TypeMapDemo.java
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException { Properties p = new Properties(); p.load(new FileInputStream("db.properties")); Class c = Class.forName(p.getProperty("db.driver")); System.out.println("Loaded driverClass " + c.getName()); Connection con = DriverManager.getConnection(p.getProperty("db.url"), "student", "student"); System.out.println("Got Connection " + con); Statement s = con.createStatement(); int ret;//from w ww . ja v a2s . c o m try { s.executeUpdate("drop table MR"); s.executeUpdate("drop type MUSICRECORDING"); } catch (SQLException andDoNothingWithIt) { // Should use "if defined" but not sure it works for UDTs... } ret = s.executeUpdate("create type MUSICRECORDING as object (" + " id integer," + " title varchar(20), " + " artist varchar(20) " + ")"); System.out.println("Created TYPE! Ret=" + ret); ret = s.executeUpdate("create table MR of MUSICRECORDING"); System.out.println("Created TABLE! Ret=" + ret); int nRows = s.executeUpdate("insert into MR values(123, 'Greatest Hits', 'Ian')"); System.out.println("inserted " + nRows + " rows"); // Put the data class into the connection's Type Map // If the data class were not an inner class, // this would likely be done with Class.forName(...); Map map = con.getTypeMap(); map.put("MUSICRECORDING", MusicRecording.class); con.setTypeMap(map); ResultSet rs = s.executeQuery("select * from MR where id = 123"); //"select musicrecording(id,artist,title) from mr"); rs.next(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { Object o = rs.getObject(i); System.out.print(o + "(Type " + o.getClass().getName() + ")\t"); } System.out.println(); }
From source file:Main.java
public static void main(String args[]) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element results = doc.createElement("Results"); doc.appendChild(results);/* ww w . j av a2 s .c o m*/ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb"); ResultSet rs = con.createStatement().executeQuery("select * from product"); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); transformer.transform(domSource, sr); System.out.println(sw.toString()); con.close(); rs.close(); }
From source file:DemoPreparedStatementSetClob.java
public static void main(String[] args) throws Exception { String id = "0001"; String newID = "0002"; ResultSet rs = null; Connection conn = null;/*from w w w.j a v a2 s.c o m*/ PreparedStatement pstmt = null; try { conn = getConnection(); // begin transaction conn.setAutoCommit(false); String query1 = "select clob_column from clob_table where id = ?"; pstmt = conn.prepareStatement(query1); pstmt.setString(1, id); rs = pstmt.executeQuery(); rs.next(); java.sql.Clob clob = (java.sql.Clob) rs.getObject(1); String query = "insert into clob_table(id, clob_column) values(?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, newID); pstmt.setClob(2, clob); int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:DemoPreparedStatementSetClob.java
public static void main(String[] args) throws Exception { String id = "0001"; String newID = "0002"; ResultSet rs = null; Connection conn = null;//w w w . j a v a 2s .co m PreparedStatement pstmt = null; try { conn = getConnection(); // begin transaction conn.setAutoCommit(false); String query1 = "select clob_column from clob_table where id = ?"; pstmt = conn.prepareStatement(query1); pstmt.setString(1, id); rs = pstmt.executeQuery(); rs.next(); java.sql.Clob clob = (java.sql.Clob) rs.getObject(1); String query = "insert into clob_table(id, clob_column) values(?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, newID); pstmt.setClob(2, clob); // execute query, and return number of rows created int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); // end transaction conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:InsertStores.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;//from ww w . j av a2 s .c o 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(); con.setAutoCommit(false); String insertStore1 = "INSERT INTO STORES VALUES (" + "100001, " + "ADDRESS(888, 'Main_Street', 'Rancho_Alegre', " + "'CA', '94049'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))"; stmt.addBatch(insertStore1); String insertStore2 = "INSERT INTO STORES VALUES (" + "100002, " + "ADDRESS(1560, 'Alder', 'Ochos_Pinos', " + "'CA', '94049'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))"; stmt.addBatch(insertStore2); String insertStore3 = "INSERT INTO STORES VALUES (" + "100003, " + "ADDRESS(4344, 'First_Street', 'Verona', " + "'CA', '94545'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))"; stmt.addBatch(insertStore3); String insertStore4 = "INSERT INTO STORES VALUES (" + "100004, " + "ADDRESS(321, 'Sandy_Way', 'La_Playa', " + "'CA', '94544'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))"; stmt.addBatch(insertStore4); String insertStore5 = "INSERT INTO STORES VALUES (" + "100005, " + "ADDRESS(1000, 'Clover_Road', 'Happyville', " + "'CA', '90566'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000003))"; stmt.addBatch(insertStore5); int[] updateCounts = stmt.executeBatch(); ResultSet rs = stmt.executeQuery("SELECT * FROM STORES"); System.out.println("Table STORES after insertion:"); System.out.println("STORE_NO LOCATION COF_TYPE MGR"); while (rs.next()) { int storeNo = rs.getInt("STORE_NO"); Struct location = (Struct) rs.getObject("LOCATION"); Object[] locAttrs = location.getAttributes(); Array coffeeTypes = rs.getArray("COF_TYPE"); String[] cofTypes = (String[]) coffeeTypes.getArray(); Ref managerRef = rs.getRef("MGR"); PreparedStatement pstmt = con.prepareStatement("SELECT MANAGER FROM MANAGERS WHERE OID = ?"); pstmt.setRef(1, managerRef); ResultSet rs2 = pstmt.executeQuery(); rs2.next(); Struct manager = (Struct) rs2.getObject("MANAGER"); Object[] manAttrs = manager.getAttributes(); System.out.print(storeNo + " "); System.out.print(locAttrs[0] + " " + locAttrs[1] + " " + locAttrs[2] + ", " + locAttrs[3] + " " + locAttrs[4] + " "); for (int i = 0; i < cofTypes.length; i++) System.out.print(cofTypes[i] + " "); System.out.println(manAttrs[1] + ", " + manAttrs[2]); rs2.close(); pstmt.close(); } rs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); 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] + " "); } System.err.println(""); } 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:com.kylinolap.query.QueryCli.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OPTION_METADATA);// w w w . j a va 2 s . c o m options.addOption(OPTION_SQL); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); KylinConfig config = KylinConfig .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt())); String sql = commandLine.getOptionValue(OPTION_SQL.getOpt()); Class.forName("net.hydromatic.optiq.jdbc.Driver"); File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath()); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); int n = 0; ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { n++; for (int i = 1; i <= meta.getColumnCount(); i++) { System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i)); } } } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }