List of usage examples for java.sql Statement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. 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);/* ww w .jav a2 s . com*/ } System.out.println("Last Key: " + lastKey); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement stmt = null; ResultSet rs = null;//from ww w .j a v a2 s. c o m 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); } } rs.close(); 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;/*from w w w.ja v a 2s.c om*/ try { 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:DemoGetGeneratedKeysMySQL.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement stmt = null; ResultSet rs = null;//from w w w. ja v a 2s . c o m 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:org.lisapark.octopus.util.jdbc.DaoUtils.java
/** * /* w w w . ja v a2 s .com*/ * @param query * @param identField, set to null if do not use generated keys * @return */ public static synchronized int insert(String query, String identField, Connection conn) throws SQLException { int key = 0; // try { Statement stmt = conn.createStatement(); if (identField != null) { stmt.executeUpdate(query, new String[] { identField }); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { key = rs.getInt(1); //identField); } } else { stmt.executeUpdate(query); } // // } catch (SQLException ex) { // Logger.getLogger(DaoUtils.class.getName()).log(Level.SEVERE, null, ex); // } return key; }
From source file:net.ymate.platform.persistence.jdbc.dialect.AbstractDialect.java
public Object[] getGeneratedKey(Statement statement) throws SQLException { // Statement ? List<Object> _ids = new ArrayList<Object>(); ResultSet _keyRSet = statement.getGeneratedKeys(); try {/*from w ww.ja va 2 s . c om*/ while (_keyRSet.next()) { _ids.add(_keyRSet.getObject(1)); } } finally { _keyRSet.close(); } return _ids.toArray(); }
From source file:hu.bme.mit.trainbenchmark.sql.SQLDatabaseDriver.java
@Override public Long insertVertexWithEdge(final Long sourceVertex, final String sourceVertexType, final String targetVertexType, final String edgeType) throws IOException { long newVertexId = -1; try {// w w w. j a v a2 s . c om final Statement st = con.createStatement(); st.executeUpdate(String.format("INSERT INTO `%s` VALUES ();", targetVertexType), Statement.RETURN_GENERATED_KEYS); try (ResultSet rs = st.getGeneratedKeys()) { if (rs.next()) { newVertexId = rs.getLong(1); String update; if (SENSOR_EDGE.equals(edgeType)) { update = String.format("UPDATE `%s` SET `%s` = %d WHERE `%s` = %d;", TRACKELEMENT, SENSOR_EDGE, newVertexId, ID, sourceVertex); } else { update = String.format("INSERT INTO `%s` (`%s`, `%s`) VALUES (%d, %d);", edgeType, EDGE_SOURCE_TYPES.get(edgeType), EDGE_TARGET_TYPES.get(edgeType), sourceVertex, newVertexId); } st.executeUpdate(update); } } } catch (final SQLException e) { throw new IOException(e); } return newVertexId; }
From source file:com.adaptris.core.services.jdbc.JdbcDataCaptureServiceImpl.java
protected void saveKeys(AdaptrisMessage msg, Statement stmt) throws SQLException { ResultSet rs = null;/*from w w w .java2s. co m*/ Statement savedKeysQuery = null; try { if (saveReturnedKeys()) { if (!actor.isOldJbc()) { rs = stmt.getGeneratedKeys(); rs.next(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { String name = rsmd.getColumnName(i); String value = rs.getObject(name).toString(); msg.addMetadata(name, value); } } else { savedKeysQuery = createStatement(actor.getSqlConnection()); rs = savedKeysQuery.executeQuery( "select max(" + saveReturnedKeysColumn + ") from " + saveReturnedKeysTable + ";"); rs.next(); String value = rs.getObject(saveReturnedKeysColumn).toString(); msg.addMetadata(saveReturnedKeysColumn, value); } } } finally { JdbcUtil.closeQuietly(savedKeysQuery); JdbcUtil.closeQuietly(rs); } }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java
/** Executes the given update on the Mysql database. The ResultSet returned contains * the generated keys *///from w w w . j ava 2s. c om public Object[] executeUpdate(String query, Connection conn) throws SQLException { try { log.debug("DBConnector is executing update: " + query); Statement stmt = conn.createStatement(); stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); Object[] results = { keys, stmt }; return results; } catch (SQLException e) { log.error("Failed to execute the update: " + query, e); throw e; } }
From source file:com.mirth.connect.server.util.DatabaseConnection.java
public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression) throws SQLException { Statement statement = null; try {/*from w w w .ja va2 s . com*/ statement = connection.createStatement(); logger.debug("executing update:\n" + expression); statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS); CachedRowSetImpl crs = new CachedRowSetImpl(); crs.populate(statement.getGeneratedKeys()); return crs; } catch (SQLException e) { throw e; } finally { DbUtils.closeQuietly(statement); } }