List of usage examples for java.sql Connection createStatement
Statement createStatement() throws SQLException;
Statement
object for sending SQL statements to the database. From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); String insert = "INSERT INTO orders (username, order_date) VALUES ('foobar', '2007-12-13')"; Statement stmt = conn.createStatement(); stmt.executeUpdate(insert, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); int lastKey = 1; while (keys.next()) { lastKey = keys.getInt(1);//from w w w . j ava 2s.co m } System.out.println("Last Key: " + lastKey); conn.close(); }
From source file:DemoGetGeneratedKeysMySQL.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement stmt = null;// w w w. j a va 2 s . c o m ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("insert into animals_table (name) values('newName')"); rs = stmt.getGeneratedKeys(); while (rs.next()) { ResultSetMetaData rsMetaData = rs.getMetaData(); int columnCount = rsMetaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String key = rs.getString(i); System.out.println("key " + i + " is " + key); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd"); Statement stmt = conn.createStatement(); createBlobClobTables(stmt);/*from ww w. j a v a2 s . c om*/ PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)"); File file = new File("blob.txt"); FileInputStream fis = new FileInputStream(file); pstmt.setBinaryStream(1, fis, (int) file.length()); file = new File("clob.txt"); fis = new FileInputStream(file); pstmt.setAsciiStream(2, fis, (int) file.length()); fis.close(); pstmt.execute(); ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40"); rs.next(); java.sql.Blob blob = rs.getBlob(2); java.sql.Clob clob = rs.getClob(3); byte blobVal[] = new byte[(int) blob.length()]; InputStream blobIs = blob.getBinaryStream(); blobIs.read(blobVal); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(blobVal); blobIs.close(); char clobVal[] = new char[(int) clob.length()]; Reader r = clob.getCharacterStream(); r.read(clobVal); StringWriter sw = new StringWriter(); sw.write(clobVal); r.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd"); Statement stmt = conn.createStatement(); createBlobClobTables(stmt);/*from www . j av a 2s. c om*/ PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)"); File file = new File("blob.txt"); FileInputStream fis = new FileInputStream(file); pstmt.setBinaryStream(1, fis, (int) file.length()); file = new File("clob.txt"); fis = new FileInputStream(file); pstmt.setAsciiStream(2, fis, (int) file.length()); fis.close(); pstmt.execute(); ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40"); rs.next(); java.sql.Blob blob = rs.getBlob(2); java.sql.Clob clob = rs.getClob("myClobColumn"); byte blobVal[] = new byte[(int) blob.length()]; InputStream blobIs = blob.getBinaryStream(); blobIs.read(blobVal); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(blobVal); blobIs.close(); char clobVal[] = new char[(int) clob.length()]; Reader r = clob.getCharacterStream(); r.read(clobVal); StringWriter sw = new StringWriter(); sw.write(clobVal); r.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getHSQLConnection(); System.out.println("Got Connection."); Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int,name varchar);"); st.executeUpdate("create view surveyView as (select * from survey);"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')"); CachedRowSet crs = null;/*ww w. ja v a 2 s . c om*/ RowSetMetaData rsMD = new RowSetMetaDataImpl(); rsMD.setColumnCount(2); rsMD.setColumnName(1, "id"); rsMD.setColumnType(1, Types.VARCHAR); rsMD.setColumnName(2, "name"); rsMD.setColumnType(2, Types.VARCHAR); // sets the designated column's table name, if any, to the given String. rsMD.setTableName(1, "survey"); rsMD.setTableName(2, "survey"); // use a custom made RowSetMetaData object for CachedRowSet object crs = new CachedRowSetImpl(); crs.setMetaData(rsMD); crs.moveToInsertRow(); crs.updateString(1, "1111"); crs.updateString(2, "alex"); crs.insertRow(); crs.moveToInsertRow(); crs.updateString(1, "2222"); crs.updateString(2, "jane"); crs.insertRow(); // if you want to commit changes from a CachedRowSet // object to your desired datasource, then you must // create a Connection object. // //conn = getHSQLConnection(); // moves the cursor to the remembered cursor position, usually // the current row. This method has no effect if the cursor is // not on the insert row. crs.moveToCurrentRow(); // when the method acceptChanges() is executed, the CachedRowSet // object's writer, a RowSetWriterImpl object, is called behind the // scenes to write the changes made to the rowset to the underlying // data source. The writer is implemented to make a connection to // the data source and write updates to it. crs.acceptChanges(conn); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { System.out.println("Count number of rows in a specific table!"); Connection con = null; int count = 0; Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root"); Statement st = con.createStatement(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); ResultSet res = st.executeQuery("SELECT COUNT(*) FROM EMP"); while (res.next()) { count = res.getInt(1);/*from w w w . j a va 2 s. co m*/ } System.out.println("Number of row:" + count); }
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);/*w w w. ja va 2s .co 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:Main.java
public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null;/*from www .ja va 2 s . c om*/ Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); String sql = "DROP DATABASE STUDENTS"; stmt.executeUpdate(sql); stmt.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { String url = "jdbc:mysql://localhost/testdb"; String username = "root"; String password = ""; Class.forName("com.mysql.jdbc.Driver"); Connection conn = null; try {//w w w.ja v a 2s. co m conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); Statement st = conn.createStatement(); st.execute("INSERT INTO orders (username, order_date) VALUES ('java', '2007-12-13')", Statement.RETURN_GENERATED_KEYS); ResultSet keys = st.getGeneratedKeys(); int id = 1; while (keys.next()) { id = keys.getInt(1); } PreparedStatement pst = conn.prepareStatement( "INSERT INTO order_details (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)"); pst.setInt(1, id); pst.setString(2, "1"); pst.setInt(3, 10); pst.setDouble(4, 100); pst.execute(); conn.commit(); System.out.println("Transaction commit..."); } catch (SQLException e) { if (conn != null) { conn.rollback(); System.out.println("Connection rollback..."); } e.printStackTrace(); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null;//from ww w . ja v a2 s .c om Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "DELETE FROM Person WHERE id = 1"; stmt.executeUpdate(sql); stmt.close(); conn.close(); }