Use commit in Oracle stored procedures with caution

table of Contents

I. Introduction

Two, create a test example

1 Create a demo table

2 insert data

3 create a stored procedure

4 create java function

Three, test

1java function throws an exception, no commit in storage

2java function throws an exception, there is a commit in the storage

Four, summary


I. Introduction

Test the impact of commit in the Oracle stored procedure on the execution result of the program.

Two, create a test example

1 Create a demo table

CREATE TABLE "SCOTT"."DEMO" (
  "ID" NUMBER NOT NULL ,
  "DESC" VARCHAR2(255 BYTE) 
)

2 insert data

INSERT INTO "SCOTT"."DEMO" VALUES ('1', 'a');

3 create a stored procedure

CREATE OR REPLACE PROCEDURE "P_C"  (a in VARCHAR2)
AS
C_ID NUMBER;
BEGIN
	select max(id)+1 into C_ID from demo;
	insert into DEMO VALUES (C_ID,'a');
	commit;
	
	insert into DEMO VALUES (888,'a');

END;

4 create java function

public static void main(String[] args) throws Exception {
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        String user = "scott";
        String password = "root";
        // 连接数据库
        Connection con = DriverManager.getConnection(url, user, password);
        con.setAutoCommit(false);
        Statement statement = null;
        CallableStatement st = null;
        try {
            System.out.println(con);
            String sql2 = "insert into DEMO VALUES ((select max(id)+1 from demo),'a')";
            statement = con.createStatement();
            statement.execute(sql2);

            //调用存储过程
            String sql = "{call P_C(?)}";
            st = con.prepareCall(sql);
            st.setObject(1, "a");
            st.execute();

            //其它业务逻辑-模拟业务异常
            String a = null;
            System.out.println(a.length());

            //提交事务
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            con.rollback();
        } finally {
            statement.close();
            st.close();
            con.close();
        }

}

Three, test

1java function throws an exception, no commit in storage

No changes to the database, normal procedures

2java function throws an exception, there is a commit in the storage

The program throws a null pointer exception and does not commit the transaction. In the case of uncommitted transactions, no data is inserted into the database.

Looking at the data in the demo table, you can find that the data is partially successful, which is not the expected result.

Four, summary

Use commit with caution in stored procedures.

Guess you like

Origin blog.csdn.net/cs373616511/article/details/109547812