1

Is is possible to get the id from a MySQL table and "save" it into a variable on JDBC?

In my program, I have a JTextfield in which the user gives a ticket which will be stored on a MySQL DB. Everytime he gives a ticket, I want to get the id from my db where the ticket was inserted and not print in on teminal, but resolve it into a variable and use it on other classes also. I need it for other classes.

Is is possible?

Anjana Silva
  • 8,353
  • 4
  • 51
  • 54
vagg77
  • 97
  • 2
  • 15

2 Answers2

1

Something like this ?

    statement.executeUpdate();
    ResultSet generatedKeys = statement.getGeneratedKeys();
    long generatedId= 0L;
    if (generatedKeys.next()) {
        generatedId = generatedKeys.getLong(1);// here is your generated Id , 
    }
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Something like that?

PreparedStatement st;
        st = con.prepareStatement("SQL STATAMENT", "HERE COLUMN NAME FROM TABLE") VALUES(?)",Statement.RETURN_GENERATED_KEYS);
        st.setString(1,"Binded String Veriable");
        st.executeUpdate();
        ResultSet rs = st.executeQuery("select last_insert_id() as id from "HERE TABLE NAME"");
        if(rs.next()){
          int lastId = Integer.parseInt(rs.getString("id"));

Use PrpearedStatment to prevent SQL Injection for example:
st = con.prepareStatement("INSERT INTO component(user) VALUES(?)", Statement.RETURN_GENERATED_KEYS ) st.setString(1,username)

Here you have how last_insert_id() works: JDBC LAST INSER ID AND OTHER