Oracle Java JDBC: Get Primary Key Of Inserted Record

Here is a small write-up which should help those who still write plain Java JDBC code. I know we have some wonderful persistence frameworks like Hibernate that make ones life comfortable but the reality is we still have to deal with plain old JDBC apis. If you are poor chap like me, below code should make your life easy.

Problem statement:

I just inserted a record in Oracle database using Java JDBC. The primary key column was auto populated by a sequence value. How should I get the last inserted records auto generated primary key?

Solution:

The solution should be getGeneratedKeys(). This method was added in JDBC 3.0 and it should be used to get last auto generated key value.

See code snippet below:

PreparedStatement prepareStatement = connection.prepareStatement("insert...",

        new String[] { "your_primary_key_column_name" });

prepareStatement.executeUpdate();

ResultSet generatedKeys = prepareStatement.getGeneratedKeys();

if (null != generatedKeys && generatedKeys.next()) {

     Long primaryKey = generatedKeys.getLong(1);

}

The above code should give us auto generated primary key value. The one thing to note here is method prepareStatement(). We passed two arguments first the insert query string and second an array of column name. The column name should be the primary key column name of table where you inserting the record.

Check below source code to see complete solution.

Full solution

We have a database table called STUDENTS. We also have an oracle sequence called STUDENT_SEQ that we uses to generate primary key for STUDENTS table.

CREATE TABLE STUDENTS

(

   STUDENT_ID   NUMBER NOT NULL PRIMARY KEY,

   NAME         VARCHAR2 (50 BYTE),

   EMAIL        VARCHAR2 (50 BYTE),

   BIRTH_DATE   DATE

);

CREATE SEQUENCE STUDENT_SEQ

   START WITH 0

   MAXVALUE 9999999999999999999999999999

   MINVALUE 0;

In Java, we use plain JDBC calls to insert a record in STUDENTS table. We uses sequence STUDENT_SEQto generate primary key. Once the record is inserted, we want the last inserted primary value.

String QUERY = "INSERT INTO students "+

               "  VALUES (student_seq.NEXTVAL,"+

               "         ‘Harry‘, ‘[email protected]‘, ‘31-July-1980‘)";

// load oracle driver

Class.forName("oracle.jdbc.driver.OracleDriver");

// get database connection from connection string

Connection connection = DriverManager.getConnection(

        "jdbc:oracle:thin:@localhost:1521:sample", "scott", "tiger");

// prepare statement to execute insert query

// note the 2nd argument passed to prepareStatement() method

// pass name of primary key column, in this case student_id is

// generated from sequence

PreparedStatement ps = connection.prepareStatement(QUERY,

        new String[] { "student_id" });

// local variable to hold auto generated student id

Long studentId = null;

// execute the insert statement, if success get the primary key value

if (ps.executeUpdate() > 0) {

    // getGeneratedKeys() returns result set of keys that were auto

    // generated

    // in our case student_id column

    ResultSet generatedKeys = ps.getGeneratedKeys();

    // if resultset has data, get the primary key value

    // of last inserted record

    if (null != generatedKeys && generatedKeys.next()) {

        // voila! we got student id which was generated from sequence

        studentId = generatedKeys.getLong(1);

    }

}

The above code is filled with comments and is pretty self explanatory. Finally we have last inserted value in studentId variable.

The getGeneratedKeys() method is key here. It gives us the result set of all auto generated key values. In our case as we have only one auto generated value (for student_id column) we get only single record in this result set.

时间: 2024-10-09 23:03:00

Oracle Java JDBC: Get Primary Key Of Inserted Record的相关文章

Oracle之主键(Primary Key)用法详解

Oracle/PLSQL: 主键(Primary Key)用法 1 目标 通过示例讲解如何创建.删除.禁用和开启主键. 2 前言之-什么是主键 在Oracle中,主键指能唯一标识一条记录的单个数据表列或联合的数据表列(联合主键|复合主键).主键用到的数据表列数据不能包含空值.而且,一张表只能包含一个主键. 说明:在Oracle数据库中,联合主键的列不能超过32个.主键可以在创建表时定义或者通过ALTER TABLE语法定义. 3 创建主键之 - 在创建表时定义主键 单列主键示例: CREATE

Java JDBC链接Oracle数据库

package com.test.test; import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql

oracle约束总结(not null/unique/primary key/foreign key/check)

约束(constraint):对创建的表的列属性.字段进行的限制.诸如:not null/unique/primary key/foreign key/check 作用范围: ①列级约束只能作用在一个列上 ②表级约束可以作用在多个列上(当然表级约束也可以作用在一个列上) 定义方式:列约束必须跟在列的定义后面,表约束不与列一起,而是单独定义. - -NOT NULL:不为空约束,只能定义在列级 CREATE TABLE employees( employee_id NUMBER(6), --<sp

Oracle使用JDBC进行增删改查

Oracle使用JDBC进行增删改查 数据库和表 table USERS (   USERNAME VARCHAR2(20) not null,   PASSWORD VARCHAR2(20) ) alter table USERS   add constraint U_PK primary key (USERNAME) /**  * JdbcExample.java  *  * Provider: CoderDream's Studio  *  * History  *    Date(DD/

Get Primary Key Column From A Table

import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main { public static void main(String[] args) throws Exception { Connection conn = getHSQL

java JDBC操作MySQL数据库

一,首先在MYSQL建立一个数据库,例如Geek99DB: create database Geek99DB; use Geek99DB; 然后建立一个表CustomerTab: create table CustomerTab(id int primary key auto_increment,name varcahr(20),email varchar(20)); 显示表: show tables: 添加元素: insert into CustomerTbl(name,email)value

Java JDBC 操作

1.简介 JDBC(Java DataBase Connectivity) 是一种可用于执行SQL语句的Java API,是一套面向对象的应用程序接口, 统一了数据库的访问方式,数据库厂商提供了实现接口的类,称为'驱动程序'.因此JDBC并不能直接访问数据库, 需要依赖数据库厂商提供的JDBC驱动程序. --SQL语言: 数据定义语言(Data Definition Language,DDL)如:create,alter,drop等 数据操纵语言(Data Manipulation Langua

java:jdbc+servlet+jsp+mysql

先在mysql新增数据库和表先,把下面的几句代码复制去到mysql运行就可以创建成功了!  创建数据库 create database jdbc01 character set utf8 collate utf8_general_ci; 创建表: use  jdbc01; create table users(        id int primary key,        name varchar(40),        password varchar(40),        email

Java学习-050-AES256 之 java.security.InvalidKeyException: Illegal key size or default parameters 解决方法

在进行 Java AES 加密测试时,出现如下错误信息: java.security.InvalidKeyException: Illegal key size or default parameters at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1026) at javax.crypto.Cipher.implInit(Cipher.java:801) at javax.crypto.Cipher.chooseProvider(Cip