FRIDY
FRIDY

Reputation: 61

How to get current row inserted

I have a table, and in it I have UsernameID,UniqueID, component, coorX, coorY, coorX2, coorY2.
The UniqueID is created by Auto Increment. I want to get the current row after I insert into my table. How do I insert the current row in MySQL? I'm using Java.

In php they used

mysql_insert_id()

Can you give me an example of a script to insert the current row in MySQL using Java?

Upvotes: 1

Views: 159

Answers (2)

Manisha Srivastava
Manisha Srivastava

Reputation: 757

You can also use PreparedStatement  for the same.

String ColumnsArray[] = {"columnName"};
String sqlQuery = " " // write your insert query here
PreparedStatement pstmt = conn.prepareStatement(sql,ColumnsArray);
pstmt.setString(1, "anyvalue");

pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136092

It's JDBC standard feature, see Statement.executeUpdate(String sql, int autoGeneratedKeys), example:

    Statement stmt = conn.createStatement();
    stmt.executeUpdate("insert into t1 (UsernameID) values (1)", Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stmt.getGeneratedKeys();
    rs.next();
    long id = rs.getLong(1);

Upvotes: 1

Related Questions