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: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 . j av a 2 s. co m*/ } System.out.println("Last Key: " + lastKey); 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 www. j a v a 2 s. 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:AutoGenKeys.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null;/*from w w w .j ava 2 s . com*/ PreparedStatement pstmt; String insert = "INSERT INTO COFFEES VALUES ('HYPER_BLEND', " + "101, 10.99, 0, 0)"; String update = "UPDATE COFFEES SET PRICE = ? WHERE KEY = ?"; 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"); pstmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS); pstmt.executeUpdate(); ResultSet keys = pstmt.getGeneratedKeys(); int count = 0; keys.next(); int key = keys.getInt(1); pstmt = con.prepareStatement(update); pstmt.setFloat(1, 11.99f); pstmt.setInt(2, key); pstmt.executeUpdate(); keys.close(); pstmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } }
From source file:com.sql.EMail.java
/** * Inserts email message into email table. * * @param eml EmailMessageModel/*from w ww . ja v a 2 s . c om*/ * @return Integer - generated key of the email */ public static int InsertEmail(EmailMessageModel eml) { Connection conn = null; PreparedStatement ps = null; try { conn = DBConnection.connectToDB(); String sql = "INSERT INTO EMail (" + "section, " + "emailFrom, " + "emailTo, " + "emailSubject, " + "sentDate, " + "receivedDate, " + "emailCC, " + "emailBCC, " + "emailBody, " + "emailBodyFileName, " + "readyToFile " + ") VALUES (" + "?, " //1 + "?, " //2 + "?, " //3 + "?, " //4 + "?, " //5 + "?, " //6 + "?, " //7 + "?, " //8 + "?, " //9 + "?, " //10 + "0)"; // Ready to File False ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, StringUtils.left(eml.getSection(), 4)); ps.setString(2, StringUtils.left(eml.getEmailFrom(), 200)); ps.setString(3, eml.getEmailTo()); ps.setString(4, eml.getEmailSubject()); ps.setTimestamp(5, eml.getSentDate()); ps.setTimestamp(6, eml.getReceivedDate()); ps.setString(7, eml.getEmailCC()); ps.setString(8, eml.getEmailBCC()); ps.setString(9, eml.getEmailBody()); ps.setString(10, eml.getEmailBodyFileName()); ps.executeUpdate(); ResultSet newRow = ps.getGeneratedKeys(); if (newRow.next()) { return newRow.getInt(1); } } catch (SQLException ex) { ExceptionHandler.Handle(ex); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(ps); } return 0; }
From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java
public static int insertIntoOuvragetype(DataSource ds, String contenu_commentaire, int utilisateurid, int ouvrageid) throws SQLException { Connection con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO ouvragetype (contenu_commentaire, utilisateurid, ouvrageid)" + "VALUES (?, ?, ?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, contenu_commentaire); statement.setInt(2, utilisateurid);/*from www . java 2 s . co m*/ statement.setInt(3, ouvrageid); statement.execute(); ResultSet auto = statement.getGeneratedKeys(); if (auto.next()) { generatedId = auto.getInt(1); } else { generatedId = -1; } statement.close(); con.close(); return generatedId; }
From source file:org.biblionum.ouvrage.modele.CategorieOuvrageModele.java
/** * Java method that inserts a row in the generated sql table and returns the * new generated id/*from w ww. java 2s . c o m*/ * * @param con (open java.sql.Connection) * @param designation_categorie * @return id (database row id [id]) * @throws SQLException */ public static int insertIntoCategorieouvrage(DataSource ds, String designation_categorie) throws SQLException { con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO categorieouvrage (designation_categorie)" + "VALUES (?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, designation_categorie); statement.execute(); ResultSet auto = statement.getGeneratedKeys(); if (auto.next()) { generatedId = auto.getInt(1); } else { generatedId = -1; } statement.close(); con.close(); return generatedId; }
From source file:mupomat.controller.ObradaOperater.java
@Override public Operater dodajNovi(Operater entitet) { try {//from w w w .jav a2 s .c om Connection veza = MySqlBazaPodataka.getConnection(); PreparedStatement izraz = veza.prepareStatement( "insert into operater (korisnickoime,lozinka,ime,prezime,aktivan) values (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); izraz.setString(1, entitet.getKorisnickoIme()); izraz.setString(2, DigestUtils.md5Hex(entitet.getLozinka())); izraz.setString(3, entitet.getIme()); izraz.setString(4, entitet.getPrezime()); izraz.setBoolean(5, entitet.isAktivan()); izraz.executeUpdate(); ResultSet rs = izraz.getGeneratedKeys(); rs.next(); entitet.setSifra(rs.getInt(1)); rs.close(); izraz.close(); veza.close(); } catch (Exception e) { // System.out.println(e.getMessage()); e.printStackTrace(); return null; } return entitet; }
From source file:mx.com.pixup.portal.dao.DisqueraDaoJdbc.java
@Override public Disquera insertDisquera(Disquera disquera) { Connection connection = DBConecta.getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null;//from w ww .ja v a2 s .c om String sql = "insert into disquera (nombre) values (?)"; try { preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, disquera.getNombre()); preparedStatement.execute(); resultSet = preparedStatement.getGeneratedKeys(); resultSet.next(); disquera.setId(resultSet.getInt(1)); return disquera; } catch (Exception e) { Logger.getLogger(DBConecta.class.getName()).log(Level.SEVERE, null, e); return null; } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } }
From source file:oobbit.orm.Links.java
/** * Add single new link.// w ww.j a v a 2 s . c om * * @param link * * @return ID of the created link * * @throws SQLException */ public int add(Link link) throws SQLException { PreparedStatement statement = getConnection().prepareStatement( "INSERT INTO `oobbit`.`links`(`link_id`,`title`,`content`,`link`,`category`,`creator`,`create_time`,`edit_time`) " + "VALUES(NULL, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, NULL);", Statement.RETURN_GENERATED_KEYS); statement.setString(1, link.getTitle()); statement.setString(2, link.getContent()); statement.setString(3, link.getUrl()); statement.setString(4, link.getCategory()); statement.setInt(5, link.getCreatorId()); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } return -1; // failed }
From source file:com.surfs.storage.common.datasource.jdbc.JdbcDao.java
@Override public Object insert(String poolName, String sql, Object... params) throws Exception { Connection conn = null;/*from w ww . j a v a 2 s . com*/ PreparedStatement ps = null; ResultSet rs = null; try { conn = getConnection(poolName); ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); for (int i = 0; i < params.length; i++) { if (params[i] instanceof String) ps.setString(i + 1, (String) params[i]); else if (params[i] instanceof Integer) ps.setInt(i + 1, (Integer) params[i]); else if (params[i] instanceof Long) ps.setLong(i + 1, (Long) params[i]); else if (params[i] instanceof Timestamp) ps.setTimestamp(i + 1, (Timestamp) params[i]); } ps.execute(); rs = ps.getGeneratedKeys(); if (rs.next()) return rs.getObject(1); return null; } catch (Exception e) { throw e; } finally { JdbcUtils.closeResultset(rs); JdbcUtils.closeStatement(ps); JdbcUtils.closeConnect(conn); } }