记一次向数据库添加记录并且获取自增ID

代码示例:使用了自定义的JDBC工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
DataSource ds = JDBCUtil.getDataSource();
String sql = "INSERT INTO user(id, username, password) VALUES (NULL, \"123\", \"123456\");";
Connection conn = null;
PreparedStatement stat = null;
try {
conn = ds.getConnection();
stat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

stat.executeUpdate();

ResultSet rs = stat.getGeneratedKeys();
while (rs.next()) {
System.out.println(rs.getInt(1));
}

} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(stat, conn);
}