C#共用DBHelper

using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Midea.MES.Server.Common.Oracle
{

    /// <summary>
    /// </summary>
    public class DBHelper
    {
        public static DataSet GetDataSet(string strConn, string strSql, Params ps = null)
        {
            DataTableSchema schema = null;
            return GetDataSet(strConn, strSql, out schema, ps);
        }
        public static DataSet GetDataSet(string strConn, string strSql, out DataTableSchema dts, Params ps = null)
        {
            OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder(strConn);
            ocsb.ConnectionLifeTime = 2;//
            ocsb.MetadataPooling = false;//不缓存查询语句返回的表结构信息(因为表结构改变后,查询结果将改变)
            dts = null;
            DataSet dsRet = new DataSet("ds");
            using (OracleConnection conn = new OracleConnection(ocsb.ConnectionString))
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandText = strSql;
                PrepareCommandParameters(cmd, ps);
                using (OracleDataReader sdr = cmd.ExecuteReader())
                {
                    string tbName = string.Format("dt{0}", dsRet.Tables.Count);
                    DataTable dtRet = new DataTable(tbName);
                    var dtSchema = sdr.GetSchemaTable();
                    if (dtSchema != null)
                    {
                        dts = new DataTableSchema(dtSchema, dtRet);
                        foreach (var s in dts)
                        {
                            dtRet.Columns.Add(s.ColumnName, s.DataType);
                        }
                        while (sdr.Read())
                        {
                            DataRow dr = dtRet.NewRow();
                            object[] objs = new object[sdr.FieldCount];
                            sdr.GetValues(objs);
                            dr.ItemArray = objs;
                            dtRet.Rows.Add(dr);
                        }
                        dtRet.AcceptChanges();
                        dsRet.Tables.Add(dtRet);
                    }
                    sdr.Close();
                }
                cmd.Dispose();
                conn.Close();
            }
            dsRet.AcceptChanges();
            return dsRet;
        }
        public static DataTableSchema GetDataTableSchema(string strConn, string tbName, string tbComments = "")
        {
            DataTableSchema dts;
            GetDataSet(strConn, string.Format("SELECT * FROM {0} WHERE 1=0", tbName), out dts);
            dts.TableComments = tbComments;
            dts.TableName = tbName;
            DataTable colComments = GetDataTable(strConn, string.Format("SELECT C.COLUMN_NAME,C.DATA_TYPE,C.DATA_LENGTH,C.DATA_PRECISION,C.DATA_SCALE,C.DEFAULT_LENGTH,C.DATA_DEFAULT,S.COMMENTS  FROM USER_TAB_COLS C LEFT JOIN USER_COL_COMMENTS S ON S.COLUMN_NAME = C.COLUMN_NAME AND S.TABLE_NAME = C.TABLE_NAME WHERE C.TABLE_NAME='{0}'", tbName));
            foreach (DataRow dr in colComments.Rows)
            {
                var colName = dr["COLUMN_NAME"].ToString().ToUpper();
                var col = dts[colName];
                col.DATA_TYPE = dr["DATA_TYPE"].ToString();
                col.DATA_DEFAULT = dr["DATA_DEFAULT"].ToString();
                if (string.IsNullOrEmpty(dr["DATA_PRECISION"].ToString()))
                {
                    col.NumericPrecision = 0;
                }
                else
                {
                    col.NumericPrecision = Convert.ToInt16(dr["DATA_PRECISION"]);
                }
                if (string.IsNullOrEmpty(dr["DATA_SCALE"].ToString()))
                {
                    col.NumericScale = 0;
                }
                else
                {
                    col.NumericScale = Convert.ToInt16(dr["DATA_SCALE"]);
                }
                col.ColumnComments = dr["COMMENTS"].ToString();
            }

            DataTable dtPKCols = GetDataTable(strConn, string.Format(@"SELECT cc.COLUMN_NAME,cc.POSITION,c.CONSTRAINT_NAME FROM user_constraints c 
LEFT JOIN user_cons_columns cc ON cc.OWNER = c.OWNER AND cc.CONSTRAINT_NAME = c.CONSTRAINT_NAME AND cc.TABLE_NAME = c.TABLE_NAME
WHERE c.CONSTRAINT_TYPE='P' AND c.TABLE_NAME='{0}'
ORDER BY cc.POSITION", tbName));
            dts.TablePKCols = new List<string>();
            if (dtPKCols.Rows.Count > 0)
            {
                dts.TablePKConstraintName = dtPKCols.Rows[0]["CONSTRAINT_NAME"].ToString();
                foreach (DataRow dr in dtPKCols.Rows)
                {
                    var colName = dr["COLUMN_NAME"].ToString().ToUpper();
                    dts.TablePKCols.Add(colName);
                    dts[colName].IsKey = true;
                }
            }
            return dts;
        }
        public static DataTable GetDataTable(string strConn, string strSql, Params ps = null)
        {
            DataSet ds = GetDataSet(strConn, strSql, ps);
            return ds.Tables[0];
        }
        public static object GetSingle(string strConn, string strSql, Params ps = null)
        {
            DataSet ds = GetDataSet(strConn, strSql, ps);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0][0];
            }
            return null;
        }


        public static DataSet QueryDS(string strConn, string strSql, Params ps = null)
        {
            OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder(strConn);
            DataSet ds = new DataSet("ds");
            using (OracleConnection conn = new OracleConnection(ocsb.ConnectionString))
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                OracleDataAdapter oda = new OracleDataAdapter(strSql, conn);
                PrepareCommandParameters(oda.SelectCommand, ps);
                oda.Fill(ds);
            }
            return ds;
        }
        public static DataSet QueryDS(string strConn, string strSql, out DataTableSchema dts, Params ps = null)
        {
            OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder(strConn);
            dts = null;
            DataSet ds = new DataSet("ds");
            using (OracleConnection conn = new OracleConnection(ocsb.ConnectionString))
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                OracleDataAdapter oda = new OracleDataAdapter(strSql, conn);
                PrepareCommandParameters(oda.SelectCommand, ps);
                oda.Fill(ds);
                var dtSchema = oda.SelectCommand.ExecuteReader(CommandBehavior.KeyInfo).GetSchemaTable();
                if (dtSchema != null)
                {
                    dts = new DataTableSchema(dtSchema, ds.Tables[0]);
                }
            }
            return ds;
        }
        public static DataTable Query(string strConn, string strSql, Params ps = null)
        {
            DataSet ds = QueryDS(strConn, strSql, ps);
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            throw new Exception("此查询无结果表!");
        }
        public static List<TModel> QueryEntitys<TModel>(string strConn, string strSql, Params ps = null) where TModel : new()
        {
            var dt = Query(strConn, strSql, ps);
            return dt.ToEntityList<TModel>();
        }
        public static TModel QueryEntity<TModel>(string strConn, string strSql, Params ps = null) where TModel : new()
        {
            var list = QueryEntitys<TModel>(strConn, strSql, ps);
            if (list.Count > 0)
            {
                return list[0];
            }
            return default(TModel);
        }
        public static object QuerySingle(string strConn, string strSql, Params ps = null)
        {
            var ds = QueryDS(strConn, strSql, ps);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Columns.Count > 0)
                {
                    return ds.Tables[0].Rows[0][0];
                }
            }
            return null;
        }


        public static int ExecuteSql(string strConn, string strSql, Params ps = null)
        {
            TableSql ts = new TableSql();
            ts.Sql = strSql;
            ts.ParamsList.Add(ps);
            return ExecuteSql(strConn, ts);
        }
        public static int ExecuteSql(string strConn, string strSql, bool autoSplit, Params ps = null)
        {
            if (autoSplit)
            {
                TableSqls tss = new TableSqls();
                var sqls = strSql.SplitOracleSql();
                foreach (var sql in sqls)
                {
                    TableSql ts = new TableSql();
                    ts.Sql = sql;
                    ts.ParamsList.Add(ps);
                    tss.Add(ts);
                }
                return ExecuteSql(strConn, tss);
            }
            else
            {
                return ExecuteSql(strConn, strSql, ps);
            }
        }
        public static int ExecuteSql(string strConn, TableSql ts)
        {
            TableSqls tss = new TableSqls();
            tss.Add(ts);
            return ExecuteSql(strConn, tss);
        }
        public static int ExecuteSql(string strConn, TableSqls tss)
        {
            using (OracleConnection conn = new OracleConnection(strConn))
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                if (tss.Count == 0)
                {
                    throw new Exception("无查询语句!");
                }
                else
                {
                    int iCount = 0;
                    foreach (var ts in tss)
                    {
                        foreach (var ps in ts.ParamsList)
                        {
                            PrepareCommandParameters(cmd, ps);
                            cmd.CommandText = ts.Sql;
                            iCount += cmd.ExecuteNonQuery();
                        }
                    }
                    return iCount;
                }
            }
        }
        static void PrepareCommandParameters(OracleCommand cmd, Params ps)
        {
            cmd.Parameters.Clear();
            cmd.BindByName = true;
            if (ps != null)
            {
                foreach (var p in ps)
                {
                    cmd.Parameters.Add(new OracleParameter(p.Name, p.Value));
                }
            }
        }



        public static object ExecProcSingle(string strConn, string procName, Params ps = null)
        {
            var dt = ExecProc(strConn, procName, ps);
            if (dt.Rows.Count > 0 && dt.Columns.Count > 0)
            {
                return dt.Rows[0][0];
            }
            return null;
        }

        public static TModel ExecProcEntity<TModel>(string strConn, string procName, Params ps = null) where TModel : new()
        {
            var list = ExecProcEntitys<TModel>(strConn, procName, ps);
            if (list.Count > 0)
            {
                return list[0];
            }
            return default(TModel);
        }

        public static List<TModel> ExecProcEntitys<TModel>(string strConn, string procName, Params ps = null) where TModel : new()
        {
            var dt = ExecProc(strConn, procName, ps);
            return dt.ToEntityList<TModel>();
        }

        public static DataTable ExecProc(string strConn, string procName, Params ps = null)
        {
            var ds = ExecProcDS(strConn, procName, ps);
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return new DataTable();
        }

        public static DataSet ExecProcDS(string strConn, string procName, Params ps = null)
        {
            using (OracleConnection conn = new OracleConnection(strConn))
            {
                using (OracleCommand cmd = new OracleCommand(procName, conn))
                {
                    using (OracleDataAdapter oda = new OracleDataAdapter(cmd))
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.StoredProcedure;
                        OracleCommandBuilder.DeriveParameters(cmd);
                        if (ps != null)
                        {
                            foreach (var p in ps)
                            {
                                if (p.Direction == ParamDirection.Input || p.Direction == ParamDirection.InputOutput)
                                {
                                    if (cmd.Parameters.Contains(p.Name))
                                    {
                                        cmd.Parameters[p.Name].Value = p.Value;
                                    }
                                    else
                                    {
                                        throw new Exception(string.Format("调用存储过程时,提供了多余的参数“{0}”!", p.Name));
                                    }
                                }
                            }
                        }
                        DataSet ds = new DataSet();
                        oda.Fill(ds);
                        if (ps != null)
                        {
                            foreach (var p in ps)
                            {
                                if (p.Direction != ParamDirection.Input)
                                {
                                    p.Value = cmd.Parameters[p.Name].Value;
                                }
                            }
                        }
                        conn.Close();
                        return ds;
                    }
                }
            }
        }
    }

    public static class DataTableEx
    {
        public static TableSqls GenerateSql(this DataTable dt, string tbName, string pkcol)
        {
            return GenerateSql(dt, tbName, new string[] { pkcol });
        }
        public static TableSqls GenerateSql(this DataTable dt, string tbName, string[] pkcols)
        {
            TableSqls sqls = new TableSqls();
            sqls.Add(dt.GenerateDelete(tbName, pkcols));
            sqls.Add(dt.GenerateUpdate(tbName, pkcols));
            sqls.Add(dt.GenerateInsert(tbName));
            return sqls;
        }
        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static TableSql GenerateInsert(this DataTable dt, string tbName)
        {
            var cols = GetCompressColumnName(dt);
            var insertCols = new List<string>();
            var insertValues = new List<string>();
            foreach (var item in cols)
            {
                insertCols.Add(item.Key);
                insertValues.Add(":" + item.Value);
            }
            var ts = new TableSql();
            ts.Sql = string.Format("Insert Into {0}({1})Values({2})", tbName, string.Join(",", insertCols), string.Join(",", insertValues));
            ts.OperateType = OperateType.Add;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var dr = dt.Rows[0];
                if (dr.RowState == DataRowState.Added)
                {
                    var ps = new Params();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ps.Add(new Param() { Name = cols[dc.ColumnName], Value = dr[dc.ColumnName] });
                    }
                    ts.ParamsList.Add(ps);
                }
            }
            return ts;
        }

        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static TableSql GenerateUpdate(this DataTable dt, string tbName, string pkcol)
        {
            return GenerateUpdate(dt, tbName, new string[] { pkcol });
        }

        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static TableSql GenerateUpdate(this DataTable dt, string tbName, string[] pkcols)
        {
            var cols = GetCompressColumnName(dt);
            var dicPKS = new Dictionary<string, object>();
            foreach (var pkcol in pkcols)
            {
                dicPKS.Add(pkcol.ToUpper(), null);
            }
            var conditions = new List<string>();
            var updateCols = new List<string>();
            foreach (DataColumn dc in dt.Columns)
            {
                if (dicPKS.ContainsKey(dc.ColumnName.ToUpper()))
                {
                    conditions.Add(string.Format("({0}=:{1})", dc.ColumnName, cols[dc.ColumnName]));
                }
                else
                {
                    updateCols.Add(string.Format(" {0}=:{1} ", dc.ColumnName, cols[dc.ColumnName]));
                }
            }
            var ts = new TableSql();
            ts.Sql = string.Format("Update {0} Set {1} Where {2}", tbName, string.Join(",", updateCols), string.Join(" And ", conditions));
            ts.OperateType = OperateType.Update;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var dr = dt.Rows[0];
                if (dr.RowState == DataRowState.Modified)
                {
                    var ps = new Params();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ps.Add(new Param() { Name = cols[dc.ColumnName], Value = dr[dc.ColumnName] });
                    }
                    ts.ParamsList.Add(ps);
                }
            }
            return ts;
        }

        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static TableSql GenerateDelete(this DataTable dt, string tbName, string pkcol)
        {
            return GenerateDelete(dt, tbName, new string[] { pkcol });
        }

        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static TableSql GenerateDelete(this DataTable dt, string tbName, string[] pkcols)
        {
            var cols = GetCompressColumnName(dt);

            var conditions = new List<string>();
            foreach (var pkcol in pkcols)
            {
                conditions.Add(string.Format("({0}=:{1})", pkcol, cols[pkcol]));
            }
            var ts = new TableSql();
            ts.Sql = string.Format("Delete From {0} Where {1}", tbName, string.Join(" And ", conditions));
            ts.OperateType = OperateType.Delete;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var dr = dt.Rows[0];
                if (dr.RowState == DataRowState.Deleted)
                {
                    var ps = new Params();
                    foreach (var pkcol in pkcols)
                    {
                        ps.Add(new Param() { Name = cols[pkcol], Value = dr[pkcol, DataRowVersion.Original] });
                    }
                    ts.ParamsList.Add(ps);
                }
            }
            return ts;
        }

        /// <summary>
        /// KeyValuePair.Key为insert sql;KeyValuePair.Value为多个DataRow对应的参数,Params则为一条语句的参数
        /// </summary>
        public static Dictionary<string, string> GetCompressColumnName(this DataTable dt)
        {
            var dic = new Dictionary<string, string>();
            foreach (DataColumn dc in dt.Columns)
            {
                dic.Add(dc.ColumnName, "p" + dic.Count.ToString());
            }
            return dic;
        }

        /// <summary>
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<TModel> ToEntityList<TModel>(this DataTable dt) where TModel : new()
        {
            List<TModel> list = new List<TModel>();

            Type t = typeof(TModel);
            if (dt != null)
            {
                var ps = t.GetProperties();
                foreach (DataRow dr in dt.Rows)
                {
                    TModel obj = new TModel();
                    foreach (var p in ps)
                    {
                        if (p.CanWrite && dt.Columns.Contains(p.Name))
                        {
                            object value = dr[p.Name];
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, dr[p.Name], null);
                            }
                        }
                    }
                    list.Add(obj);
                }
            }
            return list;
        }
    }

    [Serializable]
    public class Param
    {
        public string Name { get; set; }
        public ParamDirection Direction { get; set; }
        public dynamic Value { get; set; }
    }

    public enum ParamDirection
    {
        /// <summary>
        /// 参数是输入参数。
        /// </summary>
        Input = 1,
        /// <summary>
        /// 参数是输出参数。
        /// </summary>
        Output = 2,
        /// <summary>
        /// 参数既能输入,也能输出。
        /// </summary>
        InputOutput = 3,
        /// <summary>
        /// 参数表示诸如存储过程、内置函数或用户定义函数之类的操作的返回值。
        /// </summary>
        ReturnValue = 6
    }

    [Serializable]
    public class Params : List<Param>
    {
        public Param this[string name]
        {
            get
            {
                foreach (var p in this)
                {
                    if (string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return p;
                    }
                }
                return null;
            }
        }

        public bool Contains(string name)
        {
            return (this[name] != null);
        }

        public Param Add(string name, ParamDirection direction = ParamDirection.Input)
        {
            var p = new Param();
            p.Name = name;
            p.Direction = direction;
            base.Add(p);
            return p;
        }

        public Param Add(string name, dynamic value, ParamDirection direction = ParamDirection.Input)
        {
            var p = Add(name, direction);
            p.Value = value;
            return p;
        }
    }

    public enum OperateType
    {
        Add = 1,
        Update = 2,
        Delete = 3
    }

    [Serializable]
    public class TableSql
    {
        public string Sql { get; set; }

        public List<Params> ParamsList { get; set; }

        public OperateType OperateType { get; set; }

        public TableSql()
        {
            Sql = "";
            ParamsList = new List<Params>();
        }
    }

    [Serializable]
    public class TableSqls : List<TableSql>
    {

    }

    public static class SqlEx
    {
        public static List<string> SplitOracleSql(this string sql)
        {
            var sqls = (sql.Trim() + Environment.NewLine).Split(new string[] { ";" + Environment.NewLine }, StringSplitOptions.None);
            List<string> list = new List<string>();
            for (int i = 0; i < sqls.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(sqls[i]))
                {
                    list.Add(sqls[i]);
                }
            }
            return list;
        }
    }

    [Serializable]
    public class DataTableSchema : IEnumerable<DataColumnSchema>
    {
        DataTable _dtSchema;
        List<DataColumnSchema> _list;
        Dictionary<string, DataColumnSchema> _cache;
        public DataTable Ownner { get; private set; }
        /// <summary>
        /// 表名,默认为空
        /// </summary>
        public string TableName { get; set; }
        /// <summary>
        /// 表注释,默认为空
        /// </summary>
        public string TableComments { get; set; }
        /// <summary>
        /// 主键列,默认为空
        /// </summary>
        public List<string> TablePKCols { get; set; }
        /// <summary>
        /// 主键约束的名称
        /// </summary>
        public string TablePKConstraintName { get; set; }
        public DataTableSchema(DataTable dtSchema, DataTable ownner)
        {
            if (dtSchema == null)
            {
                throw new ArgumentNullException("dtSchema");
            }
            if (ownner == null)
            {
                throw new ArgumentNullException("ownner");
            }
            TableName = "";
            TableComments = "";
            TablePKCols = new List<string>();
            this.Ownner = ownner;
            _dtSchema = dtSchema;
            _list = new List<DataColumnSchema>();
            _cache = new Dictionary<string, DataColumnSchema>();
            foreach (DataRow dr in _dtSchema.Rows)
            {
                DataColumnSchema s = new DataColumnSchema(dr);
                _list.Add(s);
                _cache.Add(s.ColumnName, s);
            }
        }

        public DataTableSchema Columns
        {
            get { return this; }
        }

        public DataColumnSchema this[int idx]
        {
            get
            {
                if (idx >= 0 && idx < _list.Count)
                {
                    return _list[idx];
                }
                return null;
            }
        }

        public DataColumnSchema this[string columnName]
        {
            get
            {
                DataColumnSchema dcs = null;
                _cache.TryGetValue(columnName, out dcs);
                return dcs;
            }
        }

        public int Count
        {
            get { return _list.Count; }
        }

        IEnumerator<DataColumnSchema> IEnumerable<DataColumnSchema>.GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        public string GenerateTableCreateSql(string tbName)
        {
            List<string> cols = new List<string>();
            foreach (var item in _list)
            {
                cols.Add(item.GetDefinitionSql() + Environment.NewLine);
            }
            return string.Format("CREATE TABLE {0}({1})", tbName, string.Join(",", cols));
        }
    }

    [Serializable]
    public class DataColumnSchema
    {
        DataRow _dr;

        public DataColumnSchema(DataRow dr)
        {
            ColumnComments = string.Empty;
            _dr = dr;
            if (!_dr.Table.Columns.Contains("DATA_TYPE"))
            {
                _dr.Table.Columns.Add("DATA_TYPE", typeof(string));
            }
            if (!_dr.Table.Columns.Contains("DATA_DEFAULT"))
            {
                _dr.Table.Columns.Add("DATA_DEFAULT", typeof(string));
            }
        }

        /// <summary>
        /// 列注释,默认为空
        /// </summary>
        public string ColumnComments { get; set; }

        public String ColumnName
        {
            get
            {
                return (String)_dr["ColumnName"];
            }
        }


        public Int32 ColumnOrdinal
        {
            get
            {
                Int32 result;
                Int32.TryParse(_dr["ColumnOrdinal"].ToString(), out result);
                return result;
            }
        }


        public Int32 ColumnSize
        {
            get
            {
                Int32 result;
                Int32.TryParse(_dr["ColumnSize"].ToString(), out result);
                return result;
            }
        }


        public Int16 NumericPrecision
        {
            get
            {
                Int16 result;
                Int16.TryParse(_dr["NumericPrecision"].ToString(), out result);
                return result;
            }
            set
            {
                _dr["NumericPrecision"] = value;
            }
        }


        public Int16 NumericScale
        {
            get
            {
                Int16 result;
                Int16.TryParse(_dr["NumericScale"].ToString(), out result);
                return result;
            }
            set
            {
                _dr["NumericScale"] = value;
            }
        }


        public Boolean IsUnique
        {
            get
            {
                object obj = _dr["IsUnique"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsKey
        {
            get
            {
                object obj = _dr["IsKey"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
            set
            {
                _dr["IsKey"] = value;
            }
        }


        public Boolean IsRowID
        {
            get
            {
                object obj = _dr["IsRowID"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public String BaseColumnName
        {
            get
            {
                return (String)_dr["BaseColumnName"];
            }
        }


        public String BaseSchemaName
        {
            get
            {
                return (String)_dr["BaseSchemaName"];
            }
        }


        public String BaseTableName
        {
            get
            {
                return (String)_dr["BaseTableName"];
            }
        }


        public Type DataType
        {
            get
            {
                return (Type)_dr["DataType"];
            }
        }


        public OracleDbType ProviderType
        {
            get
            {
                return (OracleDbType)_dr["ProviderType"];
            }
        }


        public Boolean AllowDBNull
        {
            get
            {
                object obj = _dr["AllowDBNull"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsAliased
        {
            get
            {
                object obj = _dr["IsAliased"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsByteSemantic
        {
            get
            {
                object obj = _dr["IsByteSemantic"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsExpression
        {
            get
            {
                object obj = _dr["IsExpression"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsHidden
        {
            get
            {
                object obj = _dr["IsHidden"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsReadOnly
        {
            get
            {
                object obj = _dr["IsReadOnly"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }


        public Boolean IsLong
        {
            get
            {
                object obj = _dr["IsLong"];
                return obj == DBNull.Value ? false : (Boolean)obj;
            }
        }

        public string DATA_TYPE
        {
            get
            {
                return _dr["DATA_TYPE"].ToString();
            }
            set
            {
                _dr["DATA_TYPE"] = value;
            }
        }

        /// <summary>
        /// 系统表的LONG类型未能获取到值
        /// </summary>
        public string DATA_DEFAULT
        {
            get
            {
                return _dr["DATA_DEFAULT"].ToString();
            }
            set
            {
                _dr["DATA_DEFAULT"] = value;
            }
        }

        public string GetDefinitionSql()
        {
            string size = string.Empty;
            string type = this.ProviderType.ToString().ToUpper();
            switch (this.ProviderType)
            {
                case OracleDbType.BinaryDouble:
                    {
                        type = "BINARY_DOUBLE";
                    }
                    break;
                case OracleDbType.BinaryFloat:
                    {
                        type = "BINARY_FLOAT";
                    }
                    break;
                case OracleDbType.Single:
                case OracleDbType.Double:
                    {
                        type = "FLOAT";
                        size = string.Format("({0})", this.NumericPrecision);
                    }
                    break;
                case OracleDbType.Decimal:
                    {
                        type = "NUMBER";
                    }
                    break;
                case OracleDbType.Int16:
                case OracleDbType.Int32:
                case OracleDbType.Int64:
                    {
                        type = "NUMBER";
                        size = string.Format("({0})", this.NumericPrecision);
                    }
                    break;
                case OracleDbType.LongRaw:
                    {
                        type = "LONG RAW";
                    }
                    break;
                case OracleDbType.Char:
                case OracleDbType.NChar:
                case OracleDbType.Varchar2:
                case OracleDbType.NVarchar2:
                    {
                        size = string.Format("({0})", this.ColumnSize);
                    }
                    break;
                case OracleDbType.Blob:
                    break;
                case OracleDbType.Byte:
                    break;
                case OracleDbType.Clob:
                    break;
                case OracleDbType.Date:
                    break;
                case OracleDbType.BFile:
                    break;
                case OracleDbType.Long:
                    break;
                case OracleDbType.IntervalDS:
                    break;
                case OracleDbType.IntervalYM:
                    break;
                case OracleDbType.NClob:
                    break;
                case OracleDbType.Raw:
                    break;
                case OracleDbType.RefCursor:
                    break;
                case OracleDbType.TimeStamp:
                    break;
                case OracleDbType.TimeStampLTZ:
                    break;
                case OracleDbType.TimeStampTZ:
                    break;
                case OracleDbType.XmlType:
                    break;
                default:
                    break;
            }
            if (!string.IsNullOrEmpty(this.DATA_TYPE))
            {
                type = this.DATA_TYPE;
            }
            return string.Format("{0} {1} {2} {3} {4}", this.ColumnName, type, size, this.AllowDBNull ? "" : "NOT NULL", this.DATA_DEFAULT);
        }

        public string GetDefaultValueDefinitionSql()
        {
            return string.Format("{0} {1}", this.ColumnName, this.DATA_DEFAULT);
        }
    }
}

你可能感兴趣的:(return,null,public)