jdbc获取新插入记录id_如何使用Java(JDBC)在MySQL中获取最后插入的记录ID
jdbc获取新插入记录id
When we insert a record in a table that contains an auto increment column then we can easily obtain its id (primary key).
当我们在包含自动增量列的表中插入记录时,我们可以轻松获取其ID(主键)。
Below example will show you how you can get the id of last inserted record in MySQL using Java (JDBC). In my example the table has following structure. In this case id column is auto increment primary key.
下面的示例将向您展示如何使用Java(JDBC)获取MySQL中最后插入的记录的ID。 在我的示例中,表格具有以下结构。 在这种情况下, id列为自动递增主键。
如何使用Java(JDBC)在MySQL中获取最后插入的记录ID (How to Get Last Inserted Record ID in MySQL Using Java (JDBC))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import java.sql.*;
public class MySQLJavaExample {
static int getLastId(){
String URL="localhost:3306";
String USERNAME="root";
String PASSWORD="root";
String DATABASE="demo";
int id=0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://"+ URL + "/" + DATABASE,USERNAME,PASSWORD);
PreparedStatement ps=con.prepareStatement("insert into record (name) values(?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,"Neeraj");
ps.executeUpdate();
ResultSet rs=ps.getGeneratedKeys();
if(rs.next()){
id=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
public static void main(String args[]){
System.out.println("id:"+getLastId());
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import java . sql . * ;
public class MySQLJavaExample {
static int getLastId ( ) {
String URL = "localhost:3306" ;
String USERNAME = "root" ;
String PASSWORD = "root" ;
String DATABASE = "demo" ;
int id = 0 ;
try {
Class . forName ( "com.mysql.jdbc.Driver" ) ;
Connection con = DriverManager . getConnection ( "jdbc:mysql://" + URL + "/" + DATABASE , USERNAME , PASSWORD ) ;
PreparedStatement ps = con . prepareStatement ( "insert into record (name) values(?)" , Statement . RETURN_GENERATED_KEYS ) ;
ps . setString ( 1 , "Neeraj" ) ;
ps . executeUpdate ( ) ;
ResultSet rs = ps . getGeneratedKeys ( ) ;
if ( rs . next ( ) ) {
id = rs . getInt ( 1 ) ;
}
} catch ( Exception e ) {
e . printStackTrace ( ) ;
}
return id ;
}
public static void main ( String args [ ] ) {
System . out . println ( "id:" + getLastId ( ) ) ;
}
}
|
Output:
输出:
id: 3
id:3
If you have any doubts regarding above code then you can ask it by commenting below.
如果您对以上代码有任何疑问,可以通过在下面的注释中提出。
翻译自: https://www.thecrazyprogrammer.com/2015/12/get-last-inserted-record-id-in-mysql-using-java.html
jdbc获取新插入记录id