.NET/C#/Oracle数据库操作类

using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OracleClient;
using System.Text;
using System.IO;

/// 
/// Oracle数据库操作类
/// 
internal static class OracleHelper
{
    //数据库连接字符串
    private readonly static string connstr = ConfigurationManager.ConnectionStrings["ConnectionStrings"].ConnectionString;
    /// 
    /// 执行数据库查询操作,返回受影响的行数
    /// 
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作影响的数据行数
    internal static int ExecuteNonQuery(string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = new OracleConnection(connstr);
        int result = 0;

        try
        {
            PrepareCommand(command, connection, null,CommandType.Text, cmdText, commandParameters);
            result = command.ExecuteNonQuery();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    /// 
    /// 执行数据库事务查询操作,返回受影响的行数
    /// 
    /// 数据库事务对象
    /// Command类型
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前事务查询操作影响的数据行数
    internal static int ExecuteNonQuery(OracleTransaction transaction, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = transaction.Connection;
        int result = 0;

        try
        {
            PrepareCommand(command, connection, transaction, cmdType, cmdText, commandParameters);
            result = command.ExecuteNonQuery();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            transaction.Dispose();
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    /// 
    /// 执行数据库查询操作,返回受影响的行数
    /// 
    /// Oracle数据库连接对象
    /// Command类型
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作影响的数据行数
    internal static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters)
    {
        if (connection == null) throw new ArgumentNullException("当前数据库连接不存在");
        OracleCommand command = new OracleCommand();
        int result = 0;

        try
        {
            PrepareCommand(command, connection, null, cmdType, cmdText, commandParameters);
            result = command.ExecuteNonQuery();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    /// 
    /// 执行数据库查询操作,返回OracleDataReader类型的内存结果集
    /// 
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作返回的OracleDataReader类型的内存结果集
    internal static OracleDataReader ExecuteReader(string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = new OracleConnection(connstr);
        OracleDataReader reader = null;

        try
        {
            PrepareCommand(command, connection, null,CommandType.Text, cmdText, commandParameters);
            reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            command.Parameters.Clear();
            return reader;
        }
        catch
        {
            command.Dispose();
            connection.Close();
            throw;
        }
    }

    /// 
    /// 执行数据库查询操作,返回DataSet类型的结果集
    /// 
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作返回的DataSet类型的结果集
    internal static DataSet ExecuteDataSet(string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = new OracleConnection(connstr);
        DataSet dataset = null;

        try
        {
            PrepareCommand(command, connection, null,CommandType.Text, cmdText, commandParameters);
            OracleDataAdapter adapter = new OracleDataAdapter();
            adapter.SelectCommand = command;
            dataset = new DataSet();
            adapter.Fill(dataset);
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return dataset;
    }

    /// 
    /// 执行数据库查询操作,返回DataTable类型的结果集
    /// 
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作返回的DataTable类型的结果集
    internal static DataTable ExecuteDataTable(string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = new OracleConnection(connstr);
        DataTable table = null;

        try
        {
            PrepareCommand(command, connection, null,CommandType.Text, cmdText, commandParameters);
            OracleDataAdapter adapter = new OracleDataAdapter();
            adapter.SelectCommand = command;
            table = new DataTable();
            adapter.Fill(table);
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return table;
    }

    /// 
    /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值
    /// 
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作返回的结果集中位于第一行第一列的Object类型的值
    internal static object ExecuteScalar(string cmdText, params OracleParameter[] commandParameters)
    {
        OracleCommand command = new OracleCommand();
        OracleConnection connection = new OracleConnection(connstr);
        object result = null;

        try
        {
            PrepareCommand(command, connection, null,CommandType.Text, cmdText, commandParameters);
            result = command.ExecuteScalar();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    ///    
    ///    执行数据库事务查询操作,返回结果集中位于第一行第一列的Object类型的值
    ///    
    ///    一个已存在的数据库事务对象
    ///    命令类型
    ///    Oracle存储过程名称或PL/SQL命令
    ///    命令参数集合
    ///    当前事务查询操作返回的结果集中位于第一行第一列的Object类型的值
    internal static object ExecuteScalar(OracleTransaction transaction, CommandType commandType, string commandText, params OracleParameter[] commandParameters)
    {
        if (transaction == null) throw new ArgumentNullException("当前数据库事务不存在");
        OracleConnection connection = transaction.Connection;
        if (connection == null) throw new ArgumentException("当前事务所在的数据库连接不存在");

        OracleCommand command = new OracleCommand();
        object result = null;

        try
        {
            PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters);
            result = command.ExecuteScalar();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            transaction.Dispose();
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    /// 
    /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值
    /// 
    /// 数据库连接对象
    /// Command类型
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    /// 当前查询操作返回的结果集中位于第一行第一列的Object类型的值
    internal static object ExecuteScalar(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters)
    {
        if (connection == null) throw new ArgumentException("当前数据库连接不存在");
        OracleCommand command = new OracleCommand();
        object result = null;

        try
        {
            PrepareCommand(command, connection, null, cmdType, cmdText, commandParameters);
            result = command.ExecuteScalar();
            command.Parameters.Clear();
        }
        catch
        {
            throw;
        }
        finally
        {
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        return result;
    }

    /// 
    /// 执行数据库命令前的准备工作
    /// 
    /// Command对象
    /// 数据库连接对象
    /// 事务对象
    /// Command类型
    /// Oracle存储过程名称或PL/SQL命令
    /// 命令参数集合
    private static void PrepareCommand(OracleCommand command, OracleConnection connection, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] commandParameters)
    {
        if (connection.State != ConnectionState.Open) connection.Open();

        command.Connection = connection;
        command.CommandText = cmdText;
        command.CommandType = cmdType;

        if (trans != null) command.Transaction = trans;

        if (commandParameters != null)
        {
            foreach (OracleParameter parm in commandParameters)
                command.Parameters.Add(parm);
        }
    }

    /// 
    /// 将.NET日期时间类型转化为Oracle兼容的日期时间格式字符串
    /// 
    /// .NET日期时间类型对象
    /// Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))
    internal static string GetOracleDateFormat(DateTime date)
    {
        return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','YYYY-MM-DD')";
    }

    /// 
    /// 将.NET日期时间类型转化为Oracle兼容的日期格式字符串
    /// 
    /// .NET日期时间类型对象
    /// Oracle日期时间类型格式化限定符
    /// Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))
    internal static string GetOracleDateFormat(DateTime date, string format)
    {
        if (format == null || format.Trim() == "") format = "YYYY-MM-DD";
        return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','" + format + "')";
    }

    /// 
    /// 将指定的关键字处理为模糊查询时的合法参数值
    /// 
    /// 待处理的查询关键字
    /// 过滤后的查询关键字
    internal static string HandleLikeKey(string source)
    {
        if (source == null || source.Trim() == "") return null;

        source = source.Replace("[", "[]]");
        source = source.Replace("_", "[_]");
        source = source.Replace("%", "[%]");

        return ("%" + source + "%");
    }

    /// 
    /// 将文本内容写入到数据库的CLOB字段中(不可用:报连接被关闭的异常)
    /// 
    /// 数据库连接字符串
    /// 数据库表名称
    /// 指定的WHERE条件语句
    /// CLOB字段的名称
    /// 要写入的文本内容
    internal static void WriteCLOB(string table, string where, string clobField, string content)
    {
        if (String.IsNullOrEmpty(connstr) || String.IsNullOrEmpty(table) || String.IsNullOrEmpty(clobField)) return;

        using (OracleConnection connection = new OracleConnection(connstr))
        {
            OracleCommand command = null;

            try
            {
                connection.Open();
                command = connection.CreateCommand();
                command.CommandText = "SELECT " + clobField + " FROM " + table + " WHERE " + where + " FOR UPDATE";
                OracleDataReader reader = command.ExecuteReader();

                if (reader != null && reader.HasRows)
                {
                    reader.Read();
                    command.Transaction = command.Connection.BeginTransaction();

                    OracleLob lob = reader.GetOracleLob(0);
                    byte[] buffer = Encoding.Unicode.GetBytes(content);
                    if (lob != OracleLob.Null) lob.Erase();
                    lob.Write(buffer, 0, ((buffer.Length % 2 == 0) ? buffer.Length : (buffer.Length - 1)));

                    command.Transaction.Commit();
                    reader.Close();
                }
            }
            catch
            {
                command.Transaction.Rollback();
                throw;
            }
            finally
            {
                command.Dispose();
                connection.Close();
                connection.Dispose();
            }
        }
    }

    /// 
    /// 从数据库中读取CLOB字段的内容并进行输出
    /// 
    /// 数据库连接字符串
    /// 数据库表名称
    /// 指定的WHERE条件语句
    /// CLOB字段的名称
    /// 保存内容输出的字符串变量
    internal static void ReadCLOB(string connectionString, string table, string where, string clobField, ref string output)
    {
        if (String.IsNullOrEmpty(connectionString) || String.IsNullOrEmpty(table) || String.IsNullOrEmpty(clobField)) return;

        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            OracleCommand command = null;
            StreamReader stream = null;

            try
            {
                connection.Open();
                command = connection.CreateCommand();
                command.CommandText = "SELECT " + clobField + " FROM " + table + " WHERE " + where;
                OracleDataReader reader = command.ExecuteReader();

                if (reader != null && reader.HasRows)
                {
                    reader.Read();
                    command.Transaction = command.Connection.BeginTransaction();

                    OracleLob lob = reader.GetOracleLob(0);
                    if (lob != OracleLob.Null)
                    {
                        stream = new StreamReader(lob, Encoding.Unicode);
                        output = stream.ReadToEnd().Trim();
                        command.Transaction.Commit();
                        reader.Close();
                    }
                }
            }
            catch
            {
                command.Transaction.Rollback();
                throw;
            }
            finally
            {
                stream.Close();
                command.Dispose();
                connection.Close();
                connection.Dispose();
            }
        }
    }
}

你可能感兴趣的:(C#/.net,DB/SQL/NoSQL)