首页 > 其他分享 >JDBC6 - 主键回显

JDBC6 - 主键回显

时间:2023-01-13 10:24:20浏览次数:48  
标签:preparedStatement 回显 JDBC6 resultSet id 获取 主键

主键回显

只发生在插入数据时,返回插入的数据在数据库中自增长的主键值

package com.atguigu.api.preparedStatement;

import org.junit.Test;

import java.sql.*;

public class PSOtherPart {

    /**
     * TODO 主键回显
     *      t_user插入一条数据,并且获取数据库自增长的主键
     *
     * TODO 使用总结
     *      1.在创建PreparedStatement的时候,传入Statement.RETURN_GENERATED_KEYS
     *        获取的结果携带数据库自增长主键
     *      2.获取司机装主键值结果集的对象,一行一列,获取对应数据即可
     *        ResultSet resultSet = preparedStatement.getGeneratedKeys();
     */

    @Test
    public void returnPrimaryKey() throws ClassNotFoundException, SQLException {

        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.获取数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu?user=root&password=123456");

        //3.编写sql语句
        String sql = "insert into t_user(account,password,nickname) values(?,?,?)";

        //4.创建PreparedStatement
        //传入Statement.RETURN_GENERATED_KEYS 从而在结果集中携带数据库自增长主键
        PreparedStatement preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

        //5.占位符赋值
        preparedStatement.setObject(1,"zzz");
        preparedStatement.setObject(2,"111111");
        preparedStatement.setObject(3,"hehe");

        //6.发送SQL语句,并获取结果
        int i = preparedStatement.executeUpdate();

        //7.解析结果集
        if(i > 0){
            System.out.println("数据插入成功");

            //可以获取回显主键
            //获取司机装主键的结果集对象,一行 一列 id=值
            ResultSet resultSet = preparedStatement.getGeneratedKeys();

            //只有一行 光标下移一次就行
            resultSet.next();
            //只有一列就是主键id
            int id = resultSet.getInt(1);

            System.out.println("id = "+id);

        }else{
            System.out.println("数据插入失败");
        }
        //8.关闭资源
        preparedStatement.close();
        connection.close();
    }

}

标签:preparedStatement,回显,JDBC6,resultSet,id,获取,主键
From: https://www.cnblogs.com/Ashen-/p/17048717.html

相关文章