jdbc 技术执行 insert 后获取自增列的值,插入操作时获取自增列的值

package com.csdn.jdbc;
import java.sql.*;
public class GetAutoColumnValues {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql:///fruitdb", "root", "123456");

        String sql = "insert into t_fruit values(0,?,?,?,?)";
        PreparedStatement psmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        //填充参数
        psmt.setString(1,"哈密瓜");
        psmt.setInt(2, 23);
        psmt.setInt(3, 230);
        psmt.setString(4, "很好吃");

        int count = psmt.executeUpdate();
        System.out.println(count > 0 ? "保存成功" : "保存失败");

        ResultSet rs = psmt.getGeneratedKeys();
        if (rs.next()) {
            long id = rs.getLong(1);
            System.out.println("这条记录的自增列的值是:" + id);
        }

        psmt.close();
    }
}