C#中使用 Oracle的事务与存储过程

1 存储过程

1.1 不带参数,没有返回值

创建表

create table test
(ID number,
NAME varchar2(10),
SEX varchar2(4),
AGE number,
ADDRESS varchar2(200)
);

创建不带参数的存储过程

create or replace procedure proc1
is
begin insert into test(ID,NAME,SEX,AGE) values
(1,'moses','man',25);
commit;
end;
/

C#代码调用

protected void Button2_Click(object sender, EventArgs e)
{
        String oc = ConfigurationManager.ConnectionStrings["conn"].ToString();
        OracleConnection conn = new OracleConnection(oc);
        conn.Open();
        OracleCommand orm = conn.CreateCommand();
        orm.CommandType = CommandType.StoredProcedure;
        orm.CommandText = "proc1";
        orm.ExecuteNonQuery();
        conn.Close();
}

1.2 没有返回值的带参数的存储过程

create or replace proc2
(v_id  number,
v_name varchar2
)
is begin insert into test(id,name)
values(v_id,v_name);
commit;
end;
/

C#调用

protected void Button1_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.TextBox2.Text))
        {
            this.TextBox2.Text = "编号不能为空";
            this.TextBox2.Focus();
            return;

        }
        if (string.IsNullOrEmpty(this.TextBox3.Text))
        {
            this.TextBox3.Text = "姓名不能为空";
            this.TextBox3.Focus();
            return;
           

        }
       String or=ConfigurationManager.ConnectionStrings["conn"].ToString();
       OracleConnection oc = new OracleConnection(or);
       oc.Open();
       OracleCommand om = oc.CreateCommand();
       om.CommandType = CommandType.StoredProcedure;
       om.CommandText = "proc2";
       om.Parameters.Add("v_id", OracleType.Number).Direction = ParameterDirection.Input;
       om.Parameters["v_id"].Value = this.TextBox2.Text.Trim();
       om.Parameters.Add("v_name", OracleType.NVarChar).Direction = ParameterDirection.Input;
       om.Parameters["v_name"].Value = this.TextBox3.Text.Trim();
       om.ExecuteNonQuery();
       oc.Close();
    }
View Code

1.3 带参数有返回值的存储过程

create or replace procedure proc3 (recount out number
)
is 
begin
select  count(*)  into reccount from test;
commit;
end;
/

C#调用

protected void Button1_Click(object sender, EventArgs e)
    {
        String or = ConfigurationManager.ConnectionStrings["conn"].ToString();
        OracleConnection oc = new OracleConnection(or);
        oc.Open();
        OracleCommand ocm = oc.CreateCommand();
        ocm.CommandType = CommandType.StoredProcedure;
        ocm.CommandText = "proc3";
        ocm.Parameters.Add("reccount", OracleType.Number).Direction = ParameterDirection.Output;
        ocm.ExecuteNonQuery();
        this.TextBox1.Text = ocm.Parameters["reccount"].Value.ToString();


       
    }
View Code

 

2 事务 (OracleTransaction )

应用程序通过针对OracleConnection对象调用 BeginTransaction 来创建OracleTransaction对象。对OracleTransaction对象执行与该事务关联的所有后续操作(例如提交或中止该事务)。

OracleTransaction的成员主要有:
属性:
          Connection,指定与该事务关联的OracleConnection对象;
          IsolationLevel,指定该事务的IsolationLevel;枚举类型,用于对事物的锁定,取值有Chaos、ReadCommited、ReadUncommited、RepeatableRead、Serializable、Unspecified。
方法:
        Commit,提交SQL数据库事务;
        Rollback , 从挂起状态回滚事务;
 

对何时使用事务来操作有以下初步认识:

对多个表同时进行操作时,其他还有何注意呢?

Connection一旦开了一个事务,则执行的命令就必须和事务相关。
要注意的是,在事务进行中,不能再对同一个数据库连接(OracleConnection)再进行事务外的数据的查询和读取,

if (trans != null)

mAdp.SelectCommand.Transaction = trans;

总结:在事务块内,如果使用同样的Connection对象查询,但不指定事务,会报错,在事务提交后,或者不使用相同的Connection的对象查询,不会报错。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using Oracle.DataAccess.Client;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Data.Common;
using System.Collections;
namespace DB_Server
{
 
    #region //操作Oracle数据库
    public class OracleDBService
    {
        public OracleDBService(string ConnectionString)
        {
            OracleConStr = ConnectionString;          
        }      
        #region//连接数据库所需变量及方法  
        private string OracleConStr = "";
        private OracleConnection conn;//创建sql连接
        private OracleCommand com;//创建sql命令对象
        private OracleDataReader dr;//创建sql数据阅读器
        private OracleDataAdapter sdr;//创建sql适配器
        private DataSet ds;//创建数据集 
         
 
        /// <summary>
        /// 创建数据库连接并打开
        /// </summary>
        public void open()
        {
            //创建连接
            conn = new OracleConnection(OracleConStr);
            if (conn.State == ConnectionState.Closed)
            {             
                conn.Open();
            }
            else if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }         
        }
        #region//事务操作数据库
        /// <summary>
        /// 提交一组(多条)SQL语句操作数据库
        /// </summary>
        /// <param name="commandStringList">SQL列表</param>
        /// <returns>执行结果</returns>
        public int UpdateBatchCommand(ArrayList commandStringList)
        {
            open();
            OracleTransaction m_OraTrans = conn.BeginTransaction();//创建事务对象
            com = new OracleCommand();
            com.Connection = conn;
            string tmpStr = "";
            int influenceRowCount = 0;
            try
            {
                foreach (string commandString in commandStringList)
                {
                    tmpStr = commandString;
                    com.CommandText = tmpStr;
                    influenceRowCount += com.ExecuteNonQuery();
                }
                m_OraTrans.Commit();
                return influenceRowCount;
            }
            catch (OracleException ex)
            {
                m_OraTrans.Rollback();
                throw ex;
            }
        }
        #endregion

 

 

参考文章

残阳飞雪,  C#调用Oracle存储过程

JoyoungC#使用事务操作ORACLE数据库

 

posted @ 2017-11-03 10:23  wenglabs  阅读(1389)  评论(0编辑  收藏  举报