程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> .net C# SqlHelper for Oracle,

.net C# SqlHelper for Oracle,

編輯:C#入門知識

.net C# SqlHelper for Oracle,


適用於Oracle的sqlhelper

需要使用ODP.Net,引用Oracle.DataAccess.dll  推薦安裝ODAC

 

代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Data;
using System.Configuration;
using Oracle.DataAccess.Client;

namespace DAL
{
    public static class SqlHelper
    {
        #region 樣本
        //標准連接-SSPI
        private static readonly string defaultConnectString = "Data Source=ORCL;Integrated Security=SSPI;";
        //標准連接
        //private static readonly string defaultConnectString = "Data Source=ORCL;User Id=UPDM;Password=1234;";
        //標准鏈接
        //private static readonly string defaultConnectString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));User Id=system;Password=1234;";
        #endregion
        #region 變量

        private static OracleConnection _con = null;  
        public static string _constr = ConfigurationManager.ConnectionStrings["orcl"].ToString();
        
        #endregion  
 
 
        #region 屬性  
  
        public static string constr
        {
            get
            {
                if (_constr == null||_constr.Equals(String.Empty))
                {
                    _constr = defaultConnectString;
                }
                return _constr;
            }
            set
            {
                _constr = value;
            }
        }

        /// <summary>  
        /// 獲取或設置數據庫連接對象  
        /// </summary>  
        public static OracleConnection Con  
        {
            get  
            {
                
                if (SqlHelper._con == null)  
                {
                    SqlHelper._con = new OracleConnection();  
                }
                if (SqlHelper._con.ConnectionString == null || SqlHelper._con.ConnectionString.Equals(string.Empty))
                {
                    SqlHelper._con.ConnectionString = SqlHelper.constr;
                }
                return SqlHelper._con;  
            }  
            set  
            {  
                SqlHelper._con = value;  
            }  
        }  
        #endregion  
 
        #region 方法  
 
        /// <summary>    
        /// 執行並返回第一行第一列的數據庫操作  
        /// </summary>  
        /// <param name="commandText">Sql語句或存儲過程名</param>  
        /// <param name="commandType">Sql命令類型</param>  
        /// <param name="param">Oracle命令參數數組</param>  
        /// <returns>第一行第一列的記錄</returns>  
        public static int ExecuteScalar(string commandText, CommandType commandType, params OracleParameter[] param)  
        {   
            int result = 0;  
            try{
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))  
                {  
                    try  
                    {  
                        cmd.CommandType = commandType;  
                        if (param!=null)  
                        {  
                            cmd.Parameters.AddRange(param);  
                        }  
                        SqlHelper.Con.Open();
                        string x = cmd.CommandText;
                        result = Convert.ToInt32(cmd.ExecuteScalar());  
                    }
                    catch
                    {
                        result = -1;
                    }  
                }  
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return result;
        }
  
        /// <summary>  
        /// 執行不查詢的數據庫操作  
        /// </summary>  
        /// <param name="commandText">Oracle語句或存儲過程名</param>  
        /// <param name="commandType">Oracle命令類型</param>  
        /// <param name="param">Oracle命令參數數組</param>  
        /// <returns>受影響的行數</returns>  
        public static int ExecuteNonQuery(string commandText, CommandType commandType, params OracleParameter[] param)  
        {  
            int result = 0;
            try
            {  
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))  
                {  
                    try  
                    {  
                        cmd.CommandType = commandType;  
                        if (param!=null)  
                        {  
                            cmd.Parameters.AddRange(param);  
                        }
                        SqlHelper.Con.Open();  
                        result = cmd.ExecuteNonQuery();  
                    }  
                    catch
                    {
                        result = -1;
                    }  
                }
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return result;  
        }

        /// <summary>
        /// 獲取數據表
        /// </summary>
        /// <param name="commandText">select命令</param>
        /// <param name="param">參數表</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string commandText,params OracleParameter[] param)
        {
            DataTable result = new DataTable();
            try
            {
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                {
                    cmd.Parameters.AddRange(param);
                    try {                        
                        OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                        adapter.Fill(result);
                    }
                    catch
                    {
                        result = null;
                    }
                }
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return result;
        }

        public static int GetNextValueInSequence(string sequenceName)
        {
            if (ExecuteScalar("select count(*) from user_objects where OBJECT_NAME=:seqName", CommandType.Text, new OracleParameter(":seqName",sequenceName)) > 0)
            {
                return ExecuteScalar("select " + sequenceName + ".nextval from dual", CommandType.Text);
            }
            else
            {
                return -1;
            }


        }

        /// <summary>
        /// 事務模式執行多行非查詢語句
        /// </summary>
        /// <param name="commandText">sql語句</param>
        /// <param name="param">參數</param>
        /// <returns>受影響行數</returns>
        public static int ExecuteNonQueryTransaction(string commandText, List<OracleParameter[]> param)
        {
            int result = 0;
            try
            {
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                {
                    SqlHelper.Con.Open();
                    cmd.Transaction = cmd.Connection.BeginTransaction();
                    try
                    {
                        foreach (OracleParameter[] par in param)
                        {
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddRange(par);
                            result += cmd.ExecuteNonQuery();
                        }
                        cmd.Transaction.Commit();
                    }
                    catch
                    {
                        result = -1;
                        try
                        {
                            cmd.Transaction.Rollback();
                        }
                        catch
                        {
                            result = -2;
                        }
                    }
                }
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return result;
        }


        /// <summary>   
        /// 執行返回一條記錄的泛型對象
        /// </summary>
        /// <typeparam name="T">泛型類型</typeparam>  
        /// <param name="reader">只進只讀對象</param>  
        /// <returns>泛型對象</returns>  
        private static T ExecuteDataReader<T>(IDataReader reader)  
        {    
            T obj = default(T);  
            try  
            {  
                Type type = typeof(T);  
                obj = (T)Activator.CreateInstance(type);//從當前程序集裡面通過反射的方式創建指定類型的對象
                //obj = (T)Assembly.Load(SqlHelper._assemblyName).CreateInstance(SqlHelper._assemblyName + "." + type.Name);//從另一個程序集裡面通過反射的方式創建指定類型的對象
                PropertyInfo[] propertyInfos = type.GetProperties();//獲取指定類型裡面的所有屬性  
                foreach (PropertyInfo propertyInfo in propertyInfos)  
                {  
                    for (int i = 0; i < reader.FieldCount; i++)  
                    {  
                        string fieldName = reader.GetName(i);  
                        if (fieldName.ToLower() == propertyInfo.Name.ToLower())  
                        {  
                            object val = reader[propertyInfo.Name];//讀取表中某一條記錄裡面的某一列  
                            if (val != null && val != DBNull.Value)  
                            {
                                Type valType = val.GetType();

                                if (valType == typeof(float) || valType == typeof(double) || valType== typeof(decimal))
                                {
                                    propertyInfo.SetValue(obj, Convert.ToDouble(val), null);
                                }
                                else if (valType == typeof(int))  
                                {  
                                    propertyInfo.SetValue(obj, Convert.ToInt32(val), null);  
                                }  
                                else if (valType == typeof(DateTime))  
                                {  
                                    propertyInfo.SetValue(obj, Convert.ToDateTime(val), null);  
                                }  
                                else if (valType == typeof(string))  
                                {  
                                    propertyInfo.SetValue(obj, Convert.ToString(val), null);  
                                }  
                            }  
                            break;  
                        }  
                    }  
                }  
            }  
            catch
            {  
                throw;  
            }  
            return obj;  
        }  
 
        /// <summary>    
        /// 執行返回一條記錄的泛型對象  
        /// </summary>  
        /// <typeparam name="T">泛型類型</typeparam>  
        /// <param name="commandText">Oracle語句或存儲過程名</param>  
        /// <param name="commandType">Oracle命令類型</param>  
        /// <param name="param">Oracle命令參數數組</param>  
        /// <returns>實體對象</returns>  
        public static T ExecuteEntity<T>(string commandText, CommandType commandType, params OracleParameter[] param)  
        {  
            T obj = default(T);  
            try
            {  
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))  
                {  
                    cmd.CommandType = commandType;  
                    cmd.Parameters.AddRange(param);  
                    SqlHelper.Con.Open();  
                    OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
                    while (reader.Read())  
                    {  
                        obj = SqlHelper.ExecuteDataReader<T>(reader);  
                    }  
                }  
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return obj;  
        }  
 
        /// <summary>  
        /// 執行返回多條記錄的泛型集合對象  
        /// </summary>  
        /// <typeparam name="T">泛型類型</typeparam>  
        /// <param name="commandText">Oracle語句或存儲過程名</param>  
        /// <param name="commandType">Oracle命令類型</param>  
        /// <param name="param">Oracle命令參數數組</param>  
        /// <returns>泛型集合對象</returns>  
        public static List<T> ExecuteList<T>(string commandText, CommandType commandType, params OracleParameter[] param)  
        {  
            List<T> list = new List<T>();  
            try
            {  
                using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))  
                {  
                    try  
                    {  
                        cmd.CommandType = commandType;
                        
                        if (param != null)  
                        {  
                            cmd.Parameters.AddRange(param);  
                        }  
                        SqlHelper.Con.Open();  
  
                        OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
                        
                        while (reader.Read())  
                        {  
                            T obj = SqlHelper.ExecuteDataReader<T>(reader);  
                            list.Add(obj);  
                        }  
                    }  
                    catch (Exception ex)  
                    {  
                        list = null;  
                    }  
                }  
            }
            finally
            {
                if (SqlHelper.Con.State != ConnectionState.Closed)
                {
                    SqlHelper.Con.Close();
                }
            }
            return list;
        }

        #endregion
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved