zoukankan      html  css  js  c++  java
  • jdbc java数据库连接 7)获取插入数据的自增长值

    我们创建一个sql表,里面的数据往往都会有自增长值。

    那么,我们用jdbc插入数据的时候,要想同时获得这个增长值。

     

       代码:

    /**
     * 
     * 这是插入一条数据的同时,获取该数据的则增长列的值(该例子的自增长列是id)
     * 
     * @author LZL
     * 
     */
    public class Auto_Increment {
    
        private static Connection conn = null;
        private static PreparedStatement stsm = null;
        private static ResultSet rs = null;
    
        @Test
        public void testGetAutoIncrement() {
            try {
                // 1:创建连接
                conn = Jdbcutil.getConnection();
    
                // 2:设置sql预编译语句
                String sql = "INSERT INTO person (NAME,sex,age) VALUES (?,?,?);";
    
                // 3:执行sql预编译语句(同时在参数中指定自增列)
                stsm = conn.prepareStatement(sql,
                        PreparedStatement.RETURN_GENERATED_KEYS);
    
                // 4:设置参数值
                stsm.setString(1, "王五");
                stsm.setString(2, "男");
                stsm.setInt(3, 22);
    
                // 5:发送参数,执行sql
                stsm.executeUpdate();
    
                // 6:执行完上面的更新数据操作后,获取自增长列
                rs = stsm.getGeneratedKeys();
                // 7:输出该数据对应的自增长列的值
                if (rs.next()) {
                    System.out.println("刚才添加的数据的自增长列值是:" + rs.getInt(1));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
            }
    
            Jdbcutil.close(conn, stsm, rs);
    
        }
    
    }
  • 相关阅读:
    列表,字典,元组,集合内置方法
    数据类型内置方法(1)
    if判断与while、for循环语句
    与用户交互、格式化输出、基本运算符
    执行python程序的两种方式
    # 操作系统与编程语言分类
    drf框架2-序列化与反序列化
    drf框架1
    前端-vue路由传参、axios前后台交互、cookie设置
    前端-vue的配置和使用
  • 原文地址:https://www.cnblogs.com/LZL-student/p/6014008.html
Copyright © 2011-2022 走看看