· 10 years ago · Apr 14, 2016, 08:12 PM
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.ResultSet;
4import java.sql.SQLException;
5import java.sql.Statement;
6
7public class JDBCGetAutoIncKeys {
8
9 private static final String DBURL =
10 "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql" +
11 "&useUnicode=true&characterEncoding=UTF-8";
12 private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
13
14 static {
15 try {
16 Class.forName(DBDRIVER).newInstance();
17 } catch (Exception e){
18 e.printStackTrace();
19 }
20 }
21
22 private static Connection getConnection()
23 {
24 Connection connection = null;
25 try {
26 connection = DriverManager.getConnection(DBURL);
27 }
28 catch (Exception e) {
29 e.printStackTrace();
30 }
31 return connection;
32 }
33
34 public static void main(String[] args) {
35 Statement stmt = null;
36 ResultSet rs = null;
37 Connection conn = null;
38 try {
39 conn = getConnection();
40 stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
41 java.sql.ResultSet.CONCUR_UPDATABLE);
42
43 stmt.executeUpdate("DROP TABLE IF EXISTS autoincSample");
44 stmt.executeUpdate(
45 "CREATE TABLE autoincSample ("
46 + "id INT NOT NULL AUTO_INCREMENT, "
47 + "data VARCHAR(64), PRIMARY KEY (id))");
48
49 stmt.executeUpdate(
50 "INSERT INTO autoincSample (data) "
51 + "values ('Record ----- 1')",
52 Statement.RETURN_GENERATED_KEYS);
53
54 rs = stmt.getGeneratedKeys();
55 while (rs.next()) {
56 System.out.println("Key returned from getGeneratedKeys():"
57 + rs.getInt(1));
58 }
59 rs.close();
60
61 }
62 catch(Exception e) {
63 e.printStackTrace();
64 }
65 finally {
66
67 if (rs != null) {
68 try {
69 rs.close();
70 } catch (SQLException ex) {
71 }
72 }
73
74 if (stmt != null) {
75 try {
76 stmt.close();
77 } catch (SQLException ex) {
78 }
79 }
80 }
81 }
82
83}