Skip to content

Instantly share code, notes, and snippets.

@precious-ming
Created September 20, 2014 07:43
Show Gist options
  • Save precious-ming/8d4e1b001e67cb481466 to your computer and use it in GitHub Desktop.
Save precious-ming/8d4e1b001e67cb481466 to your computer and use it in GitHub Desktop.
JDBC获取自动增长的主键值
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///kaishengit_db", "root", "root");
String sql = "insert into t_test(username,address) values('vv','china')";
Statement stat = conn.createStatement();
stat.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stat.getGeneratedKeys();
if(rs.next()) {
System.out.println(rs.getObject(1));
}
stat.close();
conn.close();
}
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///kaishengit_db", "root", "root");
String sql = "insert into t_test(username,address) values(?,?)";
PreparedStatement stat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stat.setString(1, "vivi");
stat.setString(2, "Jp");
stat.executeUpdate();
ResultSet rs = stat.getGeneratedKeys();
if(rs.next()) {
System.out.println(rs.getObject(1));
}
stat.close();
conn.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment