Guest User

Untitled

a guest
Sep 10th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. private static final String URL = "jdbc:mysql://localhost/exemplows";
  2. private static final String USER = "XXXXXXXX";
  3. private static final String SENHA = "XXXXXXX";
  4.  
  5. public static Connection obtemConexao() throws SQLException {
  6. try {
  7. Class.forName("com.mysql.jdbc.Driver");
  8. } catch (ClassNotFoundException e) {
  9. // TODO Auto-generated catch block e.printStackTrace();
  10. }
  11. return DriverManager.getConnection(URL, USER, SENHA);
  12. }
  13.  
  14. final String sql = "INSERT INTO minha_tabela(coluna_um, coluna_dois) VALUES(?, ?)";
  15. final Connection conn = obtemConexao();
  16. final PreparedStatement ps = conn.prepareStatement(sql);
  17. // seta os valores dos parâmetros
  18. ps.executeUpdate();
  19.  
  20. final String sql = "INSERT INTO minha_tabela(coluna_um, coluna_dois) VALUES (?, ?);";
  21. final Connection conn = obtemConexao();
  22. final PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
  23. // seta os valores dos parâmetros
  24. ps.executeUpdate();
  25. final ResultSet rs = ps.getGeneratedKeys();
  26. if (rs.next()) {
  27. final int lastId = rs.getInt(1);
  28. }
  29.  
  30. final int lastId = rs.getInt("id");
  31.  
  32. ResultSet resultSet = preparedStatement.executeQuery("SELECT LAST_INSERT_ID()");
  33. if (resultSet.next()) {
  34. novoId = resultSet.getInt("LAST_INSERT_ID()");
  35. }
  36.  
  37. Connection conexao = null;
  38. PreparedStatement pst = null;
  39. ResultSet rs = null;
Add Comment
Please, Sign In to add comment