package JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestJDBC { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace (); } //When building the table hero, set the id attribute auto_increment primary key //This location id is set to null or 0 to automatically increase String sql = "insert into hero values(0,?,?)"; try ( Connection c = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/Hero?characterEncoding=UTF-8", "root", "123"); //Set the Statement.RETURN_GENERATED_KEYS parameter PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ) { // set properties ps.setString(1, "Li Bai"); ps.setInt(2, 25); //Execute sql ps.execute(); //getGeneratedKeys() gets the result set ResultSet rs = ps.getGeneratedKeys(); while(rs.next()) { //get the value of id int id = rs.getInt(1); System.out.println(id); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace (); } } }
How to get the self-increasing id in jdbc?
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325522456&siteId=291194637
Recommended
Ranking