Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

java - Get last inserted auto increment id in mysql

I am trying to get the mysql command like mysql_insert_id(); which retrieve the last inserted row's auto_increment id. What can I do to get it in Java?

rs = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");

my lastid was declared as INT. I dono what to use in rs.get and also the parameter..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using JDBC, you can use Connection.PreparedStatement(query, int) method.

PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
pstmt.executeUpdate();  
ResultSet keys = pstmt.getGeneratedKeys();    
keys.next();  
key = keys.getInt(1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...