List of usage examples for java.sql Statement RETURN_GENERATED_KEYS
int RETURN_GENERATED_KEYS
To view the source code for java.sql Statement RETURN_GENERATED_KEYS.
Click Source Link
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 ww . j av a 2 s. c o m*/ 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:org.kawanfw.test.api.client.autogeneratedkeys.InsertPrepStatementAutoKeysTest.java
/** * Do a 100 row insert inside a loop//from ww w .j a v a2 s.c o m * * @param connection * the AceQL Connection * * @throws Exception * it any Exception occurs */ public static void insertPrepStatementExecuteUpdate(Connection connection, int valueToInsert, boolean useRawExecute, boolean autoCommitOn) throws Exception { // We can now use our Remote JDBC Connection as a regular Connection! long maxCustomerId = InsertStatementTestAutoKeysTest.getMaxCustomerId(connection); MessageDisplayer.display(""); MessageDisplayer.display("maxCustomerId: " + maxCustomerId); if (!autoCommitOn) { connection.setAutoCommit(false); } // We will do all our remote insert in a SQL Transaction try { // 1) First create a Customer String sql = "insert into customer_auto (customer_title, fname, lname, addressline, town, zipcode, phone) " + " values ( ?, ?, ?, ?, ?, ?, ? )"; MessageDisplayer.display(""); MessageDisplayer.display("Inserting " + valueToInsert + " customers..."); PreparedStatement prepStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); int i = valueToInsert; int j = 1; prepStatement.setString(j++, "Sir"); prepStatement.setNull(j++, Types.VARCHAR); prepStatement.setString(j++, "Smith_" + i); prepStatement.setString(j++, i + ", Csar Avenue"); prepStatement.setString(j++, "JavaLand_" + i); prepStatement.setString(j++, i + "45"); prepStatement.setString(j++, i + "-12345678"); int rc = -1; if (!useRawExecute) { rc = prepStatement.executeUpdate(); MessageDisplayer.display("after executeUpdate(): row count: " + rc); } else { prepStatement.execute(); rc = prepStatement.getUpdateCount(); MessageDisplayer.display("after execute(): prepStatement.getUpdateCount(): " + rc); } if (!autoCommitOn) { connection.commit(); } ResultSet keys = prepStatement.getGeneratedKeys(); long lastKey = -1; while (keys.next()) { lastKey = keys.getLong(1); } keys.close(); MessageDisplayer.display("Last Key: " + lastKey); // Don't know why: there is a bug in some engines.... // Assert.assertEquals("last key = maxCustomerId + 1", lastKey, // maxCustomerId + 1); // So do another test: Assert.assertEquals("last key >= 1", true, lastKey >= 1); prepStatement.close(); } catch (Exception e) { e.printStackTrace(); if (!autoCommitOn) { connection.rollback(); } throw e; } finally { if (!autoCommitOn) { connection.setAutoCommit(true); } } }
From source file:co.marcin.novaguilds.impl.storage.AbstractDatabaseStorage.java
/** * Prepares the statements/* w ww . ja v a 2 s . c o m*/ */ protected void prepareStatements() { try { long nanoTime = System.nanoTime(); LoggerUtils.info("Preparing statements..."); preparedStatementMap.clear(); connect(); int returnKeys = isStatementReturnGeneratedKeysSupported() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS; //Guilds insert (id, tag, name, leader, spawn, allies, alliesinv, war, nowarinv, money, points, lives, timerest, lostlive, activity, created, bankloc, slots, openinv) String guildsInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString() + "guilds` VALUES(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; PreparedStatement guildsInsert = getConnection().prepareStatement(guildsInsertSQL, returnKeys); preparedStatementMap.put(PreparedStatements.GUILDS_INSERT, guildsInsert); //Guilds select String guildsSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "guilds`"; PreparedStatement guildsSelect = getConnection().prepareStatement(guildsSelectSQL); preparedStatementMap.put(PreparedStatements.GUILDS_SELECT, guildsSelect); //Guilds delete String guildsDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "guilds` WHERE `id`=?"; PreparedStatement guildsDelete = getConnection().prepareStatement(guildsDeleteSQL); preparedStatementMap.put(PreparedStatements.GUILDS_DELETE, guildsDelete); //Guilds update String guildsUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString() + "guilds` SET `tag`=?, `name`=?, `leader`=?, `spawn`=?, `allies`=?, `alliesinv`=?, `war`=?, `nowarinv`=?, `money`=?, `points`=?, `lives`=?, `timerest`=?, `lostlive`=?, `activity`=?, `bankloc`=?, `slots`=?, `openinv`=?, `banner`=? WHERE `id`=?"; PreparedStatement guildsUpdate = getConnection().prepareStatement(guildsUpdateSQL); preparedStatementMap.put(PreparedStatements.GUILDS_UPDATE, guildsUpdate); //Players insert (id, uuid, name, guild, invitedto, points, kills, deaths) String playersInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString() + "players` VALUES(null,?,?,?,?,?,?,?)"; PreparedStatement playersInsert = getConnection().prepareStatement(playersInsertSQL, returnKeys); preparedStatementMap.put(PreparedStatements.PLAYERS_INSERT, playersInsert); //Players select String playerSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "players`"; PreparedStatement playersSelect = getConnection().prepareStatement(playerSelectSQL); preparedStatementMap.put(PreparedStatements.PLAYERS_SELECT, playersSelect); //Players update String playersUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString() + "players` SET `invitedto`=?, `guild`=?, `points`=?, `kills`=?, `deaths`=? WHERE `uuid`=?"; PreparedStatement playersUpdate = getConnection().prepareStatement(playersUpdateSQL); preparedStatementMap.put(PreparedStatements.PLAYERS_UPDATE, playersUpdate); //Players delete String playersDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "players` WHERE `id`=?"; PreparedStatement playersDelete = getConnection().prepareStatement(playersDeleteSQL); preparedStatementMap.put(PreparedStatements.PLAYERS_DELETE, playersDelete); //Regions insert (id, loc_1, loc_2, guild, world) String regionsInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString() + "regions` VALUES(null,?,?,?,?);"; PreparedStatement regionsInsert = getConnection().prepareStatement(regionsInsertSQL, returnKeys); preparedStatementMap.put(PreparedStatements.REGIONS_INSERT, regionsInsert); //Regions select String regionsSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "regions`"; PreparedStatement regionsSelect = getConnection().prepareStatement(regionsSelectSQL); preparedStatementMap.put(PreparedStatements.REGIONS_SELECT, regionsSelect); //Regions delete String regionsDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "regions` WHERE `id`=?"; PreparedStatement regionsDelete = getConnection().prepareStatement(regionsDeleteSQL); preparedStatementMap.put(PreparedStatements.REGIONS_DELETE, regionsDelete); //Regions update String regionsUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString() + "regions` SET `loc_1`=?, `loc_2`=?, `guild`=?, `world`=? WHERE `id`=?"; PreparedStatement regionsUpdate = getConnection().prepareStatement(regionsUpdateSQL); preparedStatementMap.put(PreparedStatements.REGIONS_UPDATE, regionsUpdate); //Ranks insert (id, name, guild, permissions, players, default, clone) String ranksInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString() + "ranks` VALUES(null,?,?,?,?,?,?);"; PreparedStatement ranksInsert = getConnection().prepareStatement(ranksInsertSQL, returnKeys); preparedStatementMap.put(PreparedStatements.RANKS_INSERT, ranksInsert); //Ranks select String ranksSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "ranks`"; PreparedStatement ranksSelect = getConnection().prepareStatement(ranksSelectSQL); preparedStatementMap.put(PreparedStatements.RANKS_SELECT, ranksSelect); //Ranks delete String ranksDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "ranks` WHERE `id`=?"; PreparedStatement ranksDelete = getConnection().prepareStatement(ranksDeleteSQL); preparedStatementMap.put(PreparedStatements.RANKS_DELETE, ranksDelete); //Ranks delete (guild) String ranksDeleteGuildSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "ranks` WHERE `guild`=?"; PreparedStatement ranksDeleteGuild = getConnection().prepareStatement(ranksDeleteGuildSQL); preparedStatementMap.put(PreparedStatements.RANKS_DELETE_GUILD, ranksDeleteGuild); //Ranks update String ranksUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString() + "ranks` SET `name`=?, `guild`=?, `permissions`=?, `members`=?, `def`=?, `clone`=? WHERE `id`=?"; PreparedStatement ranksUpdate = getConnection().prepareStatement(ranksUpdateSQL); preparedStatementMap.put(PreparedStatements.RANKS_UPDATE, ranksUpdate); //Log LoggerUtils.info("Statements prepared in " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - nanoTime), TimeUnit.NANOSECONDS) / 1000.0 + "s"); } catch (SQLException e) { LoggerUtils.exception(e); } }
From source file:com.softberries.klerk.dao.PeopleDao.java
@Override public void create(Person c) throws SQLException { try {/* w w w.j a v a 2 s . c o m*/ init(); st = conn.prepareStatement(SQL_INSERT_PERSON, Statement.RETURN_GENERATED_KEYS); st.setString(1, c.getFirstName()); st.setString(2, c.getLastName()); st.setString(3, c.getTelephone()); st.setString(4, c.getMobile()); st.setString(5, c.getEmail()); st.setString(6, c.getWww()); // run the query int i = st.executeUpdate(); System.out.println("i: " + i); if (i == -1) { System.out.println("db error : " + SQL_INSERT_PERSON); } generatedKeys = st.getGeneratedKeys(); if (generatedKeys.next()) { c.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no generated key obtained."); } // if the person creation was successfull, add addresses AddressDao adrDao = new AddressDao(); for (Address adr : c.getAddresses()) { adr.setPerson_id(c.getId()); adrDao.create(adr, run, conn, generatedKeys); } conn.commit(); } catch (Exception e) { // rollback the transaction but rethrow the exception to the caller conn.rollback(); e.printStackTrace(); throw new SQLException(e); } finally { close(conn, st, generatedKeys); } }
From source file:SpaceInvaders_V4.Util.DBConnect.java
/** * Submit score to database/*w w w . j a v a 2s . c om*/ * * @param userID user playerID * @param score game score * @param kills number of kill this game * @param powerUps number of powerUps collected * @param deaths number of deaths this game */ public static void submitScore(int userID, int score, int kills, int powerUps, int deaths) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; int scoreID; try { conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS); stmt = conn.prepareStatement( "INSERT INTO `spaceinvaders_entity_score` (score, kills, power_ups, deaths) VALUES (?,?,?,?);", Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, score); stmt.setInt(2, kills); stmt.setInt(3, powerUps); stmt.setInt(4, deaths); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); rs.next(); scoreID = rs.getInt(1); stmt = conn.prepareStatement( "INSERT INTO `spaceinvaders_xref_player_scores` (player_id, score_id) VALUES (?,?)"); stmt.setInt(1, userID); stmt.setInt(2, scoreID); stmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } finally { closeConnections(rs, stmt, conn); } }
From source file:com.nabla.wapp.server.database.InsertStatement.java
public int execute(final Connection conn, final T record) throws SQLException, ValidationException, InternalErrorException { Assert.argumentNotNull(conn);// w ww .ja va 2 s. c o m final List<IStatementParameter> parametersToInsert = new ArrayList<IStatementParameter>(); final ArgumentList names = new ArgumentList(); final ArgumentList values = new ArgumentList(); for (IStatementParameter parameter : parameters) { if (!parameter.include(record)) continue; parametersToInsert.add(parameter); names.add(parameter.getName()); values.add("?"); } if (parametersToInsert.isEmpty()) { if (log.isErrorEnabled()) log.error("no values to insert!!!!"); throw new InternalErrorException( Util.formatInternalErrorDescription("no parameter values given for SQL statement")); } final String sql = MessageFormat.format(sqlTemplate, names.toString(), values.toString()); if (log.isDebugEnabled()) log.debug("SQL=" + sql); final PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); try { int i = 1; for (IStatementParameter parameter : parametersToInsert) parameter.write(stmt, i++, record); if (stmt.executeUpdate() != 1) { if (log.isErrorEnabled()) log.error("failed to add record"); throw new InternalErrorException( Util.formatInternalErrorDescription("failed to execute SQL statement")); } final ResultSet rsKey = stmt.getGeneratedKeys(); try { rsKey.next(); return rsKey.getInt(1); } finally { Database.close(rsKey); } } catch (final SQLException e) { if (uniqueFieldName != null && SQLState.valueOf(e) == SQLState.INTEGRITY_CONSTRAINT_VIOLATION) { if (log.isErrorEnabled()) log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e); throw new ValidationException(uniqueFieldName, CommonServerErrors.DUPLICATE_ENTRY); } throw e; } finally { Database.close(stmt); } }
From source file:com.vaadin.tutorial.todomvc.TodoModel.java
public Todo persist(Todo todo) { if (todo.getId() < 0) { try (PreparedStatement s = conn.prepareStatement( "INSERT INTO todo(id, text, completed) VALUES (NULL, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { s.setString(1, todo.getText()); s.setBoolean(2, todo.isCompleted()); s.executeUpdate();//from w w w . j av a 2 s. c om ResultSet generatedKeys = s.getGeneratedKeys(); generatedKeys.next(); todo.setId(generatedKeys.getInt(1)); } catch (SQLException e) { throw new RuntimeException("ToDo insertion failed", e); } } else { try (PreparedStatement s = conn.prepareStatement("UPDATE todo SET text= ?,completed=? WHERE id = ?")) { s.setString(1, todo.getText()); s.setBoolean(2, todo.isCompleted()); s.setInt(3, todo.getId()); s.execute(); if (s.getUpdateCount() != 1) { throw new RuntimeException("Todo update failed (non-existing id?): " + todo); } } catch (SQLException e) { throw new RuntimeException("Todo update failed", e); } } return todo; }
From source file:oobbit.orm.Users.java
/** * Creates a user and returns its id.//from ww w.jav a 2s . c om * * @param username Username for the user * @param email Email for the user * @param password Hashed password * * @return ID of the registered user * * @throws SQLException */ public int registerNewUser(String username, String email, String password) throws SQLException { PreparedStatement statement = getConnection().prepareStatement( "INSERT INTO `oobbit`.`users` (`user_id`, `username`, `email`, `password`, `access_level`, `create_time`) VALUES (NULL, ?, ?, ?, '1', CURRENT_TIMESTAMP);", Statement.RETURN_GENERATED_KEYS); statement.setString(1, username); statement.setString(2, email); statement.setString(3, hash(password)); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } throw new SQLException("Could not add user!"); }
From source file:fr.gael.dhus.database.liquibase.CopyProductImages.java
@Override public void execute(Database database) throws CustomChangeException { PreparedStatement products = null; ResultSet products_res = null; JdbcConnection db_connection = (JdbcConnection) database.getConnection(); try {// w w w . j a va 2 s. co m products = db_connection.prepareStatement("SELECT ID,QUICKLOOK,THUMBNAIL FROM PRODUCTS"); products_res = products.executeQuery(); while (products_res.next()) { PreparedStatement copy_blob_stmt = null; ResultSet generated_key_res = null; try { Blob ql = (Blob) products_res.getObject("QUICKLOOK"); Blob th = (Blob) products_res.getObject("THUMBNAIL"); Long pid = products_res.getLong("ID"); // No images: add false flags if ((ql == null) && (th == null)) { PreparedStatement product_flags_stmt = null; // Add related flags try { product_flags_stmt = db_connection.prepareStatement( "UPDATE PRODUCTS SET THUMBNAIL_FLAG=?,QUICKLOOK_FLAG=? " + "WHERE ID=?"); product_flags_stmt.setBoolean(1, false); product_flags_stmt.setBoolean(2, false); product_flags_stmt.setLong(3, pid); product_flags_stmt.execute(); } finally { if (product_flags_stmt != null) try { product_flags_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } continue; } copy_blob_stmt = db_connection.prepareStatement( "INSERT INTO PRODUCT_IMAGES (QUICKLOOK,THUMBNAIL) " + "VALUES (?,?)", Statement.RETURN_GENERATED_KEYS); copy_blob_stmt.setBlob(1, ql); copy_blob_stmt.setBlob(2, th); copy_blob_stmt.execute(); generated_key_res = copy_blob_stmt.getGeneratedKeys(); if (generated_key_res.next()) { PreparedStatement set_product_image_id_stmt = null; Long iid = generated_key_res.getLong(1); // Add ProductImages "IMAGES" entry in product try { set_product_image_id_stmt = db_connection .prepareStatement("UPDATE PRODUCTS SET IMAGES_ID=?, THUMBNAIL_FLAG=?, " + "QUICKLOOK_FLAG=? WHERE ID=?"); set_product_image_id_stmt.setLong(1, iid); set_product_image_id_stmt.setBoolean(2, th != null); set_product_image_id_stmt.setBoolean(3, ql != null); set_product_image_id_stmt.setLong(4, pid); set_product_image_id_stmt.execute(); } finally { if (set_product_image_id_stmt != null) try { set_product_image_id_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } } else { logger.error("Cannot retrieve Image primary key for " + "product ID #" + products_res.getLong("ID")); } } finally { if (generated_key_res != null) try { generated_key_res.close(); } catch (Exception e) { logger.warn("Cannot close ResultSet !"); } if (copy_blob_stmt != null) try { copy_blob_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } } } catch (Exception e) { throw new CustomChangeException("Cannot move Blobs from product", e); } finally { if (products_res != null) { try { products_res.close(); } catch (Exception e) { logger.warn("Cannot close ResultSet !"); } } if (products != null) { try { products.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } //if (db_connection!=null) try { db_connection.close (); } // catch (Exception e) {} } }
From source file:com.hs.mail.imap.dao.MySqlMailboxDao.java
private Mailbox doCreateMailbox(final long ownerID, final String mailboxName) { final String sql = "INSERT INTO mailbox (name, ownerid, nextuid, uidvalidity) VALUES(?, ?, ?, ?)"; final long uidValidity = System.currentTimeMillis(); KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, mailboxName); pstmt.setLong(2, ownerID);//from w w w.j a v a 2 s .com pstmt.setLong(3, 1); pstmt.setLong(4, uidValidity); return pstmt; } }, keyHolder); Mailbox mailbox = new Mailbox(); mailbox.setMailboxID(keyHolder.getKey().longValue()); mailbox.setOwnerID(ownerID); mailbox.setName(mailboxName); mailbox.setNextUID(1); mailbox.setUidValidity(uidValidity); return mailbox; }