.NET-ORM Database Helper

MysqlHelper.cs

namespace Ppp.Databases.Mysql
{
    using System.Data.Common;
    using global::MySql.Data.MySqlClient;
    using global::Ppp.Databases.Extensions;

    public sealed class MysqlHelper : DatabaseHelper // SDL FOR MYSQL
    {
        protected override string LeftEscapeCharacter => "`";

        protected override string RightEscapeCharacter => "`";

        protected override DbCommand CreateCommand()
        {
            return new MySqlCommand();
        }

        protected override DbParameter CreateParameter()
        {
            return new MySqlParameter();
        }

        protected override void DeriveParameters(DbCommand command)
        {
            var cmd = command as MySqlCommand;
            if (cmd != null)
            {
                MySqlCommandBuilder.DeriveParameters(cmd);
            }
        }
    }
}

DatabaseHelper.cs

namespace Ppp.Databases.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Linq;
    using System.Reflection;
    using global::Ppp.Utilities;

    public abstract class DatabaseHelper // SDL FOR DATABASE
    {
        protected abstract string LeftEscapeCharacter { get; }

        protected abstract string RightEscapeCharacter { get; }

        protected abstract DbCommand CreateCommand();

        protected abstract DbParameter CreateParameter();

        protected abstract void DeriveParameters(DbCommand command);

        private DbCommand CreateInsertImpl(object obj, string fromTable)
        {
            if (obj == null || string.IsNullOrEmpty(fromTable))
            {
                throw new ArgumentException();
            }
            string sql = "INSERT INTO {0}({1}) VALUES({2})";
            DbCommand cmd = this.CreateCommand();
            DbParameterCollection args = cmd.Parameters;
            PropertyInfo[] props = (obj.GetType()).GetProperties();
            int len = props.Length - 1;
            string fileds = null, values = null;
            for (int i = 0; i <= len; i++)
            {
                PropertyInfo prop = props[i];
                if (i >= len)
                {
                    values += ("@" + prop.Name);
                    fileds += string.Format("{0}{1}{2}", this.LeftEscapeCharacter, prop.Name, this.RightEscapeCharacter);
                }
                else
                {
                    values += string.Format("@{0},", prop.Name);
                    fileds += string.Format("{0}{1}{2},", this.LeftEscapeCharacter, prop.Name, this.RightEscapeCharacter);
                }
                object val = prop.GetValue(obj, null);
                if (val == null)
                {
                    val = DBNull.Value;
                }
                DbParameter parameter = this.CreateParameter();
                parameter.Value = val;
                parameter.ParameterName = string.Format("@{0}", prop.Name);
                args.Add(parameter);
            }
            if (fileds != null)
            {
                while (fileds.Length > 0 && fileds[fileds.Length - 1] == ',')
                {
                    fileds = fileds.Remove(fileds.Length - 1);
                }
            }
            sql = string.Format(sql, fromTable, fileds, values);
            cmd.CommandText = sql;
            return cmd;
        }

        private DbCommand CreateInsertImpl(IList<KeyValuePair<string, object>> obj, string fromTable)
        {
            if (obj == null || string.IsNullOrEmpty(fromTable))
            {
                throw new ArgumentException();
            }
            string sql = "INSERT INTO {0}({1}) VALUES({2})";
            DbCommand cmd = this.CreateCommand();
            DbParameterCollection args = cmd.Parameters;
            int len = obj.Count - 1;
            string fileds = null, values = null;
            for (int i = 0; i <= len; i++)
            {
                var prop = obj[i];
                if (i >= len)
                {
                    values += ("@" + prop.Key);
                    fileds += string.Format("{0}{1}{2}", this.LeftEscapeCharacter, prop.Key, this.RightEscapeCharacter);
                }
                else
                {
                    values += string.Format("@{0},", prop.Key);
                    fileds += string.Format("{0}{1}{2},", this.LeftEscapeCharacter, prop.Key, this.RightEscapeCharacter);
                }
                object val = prop.Value;
                if (val == null)
                {
                    val = DBNull.Value;
                }
                DbParameter parameter = this.CreateParameter();
                parameter.Value = val;
                parameter.ParameterName = string.Format("@{0}", prop.Key);
                args.Add(parameter);
            }
            if (fileds != null)
            {
                while (fileds.Length > 0 && fileds[fileds.Length - 1] == ',')
                {
                    fileds = fileds.Remove(fileds.Length - 1);
                }
            }
            sql = string.Format(sql, fromTable, fileds, values);
            cmd.CommandText = sql;
            return cmd;
        }

        private DbCommand CreateInsertImpl(IDictionary<string, object> obj, string fromTable)
        {
            if (obj == null || string.IsNullOrEmpty(fromTable))
            {
                throw new ArgumentException();
            }
            return this.CreateInsertImpl(obj.ToList(), fromTable);
        }

        public virtual DbCommand CreateInsert(object obj, string fromTable, string primaryKey, string whereCast)
        {
            IDictionary<string, object> d = obj as IDictionary<string, object>;
            if (d != null)
            {
                return this.CreateInsertImpl(d, fromTable);
            }
            IList<KeyValuePair<string, object>> l = obj as IList<KeyValuePair<string, object>>;
            if (l != null)
            {
                return this.CreateInsertImpl(l, fromTable);
            }
            return this.CreateInsertImpl(obj, fromTable);
        }

        private DbCommand CreateUpdateImpl(IDictionary<string, object> obj, string fromTable, string primaryKey, string whereCast)
        {
            if (obj == null || obj.Count <= 0 || string.IsNullOrEmpty(fromTable) || string.IsNullOrEmpty(primaryKey))
            {
                throw new ArgumentException();
            }
            return this.CreateUpdateImpl(obj.ToList(), fromTable, primaryKey, whereCast);
        }

        private DbCommand CreateUpdateImpl(IList<KeyValuePair<string, object>> obj, string fromTable, string primaryKey, string whereCast)
        {
            if (obj == null || obj.Count <= 0 || string.IsNullOrEmpty(fromTable) || string.IsNullOrEmpty(primaryKey))
            {
                throw new ArgumentException();
            }
            string when = string.Empty, sql = string.Format("UPDATE {0} SET ", fromTable);
            DbCommand cmd = this.CreateCommand();
            DbParameterCollection args = cmd.Parameters;

            int len = obj.Count - 1;
            for (int i = 0; i <= len; i++)
            {
                var prop = obj[i];
                if (prop.Key != primaryKey)
                {
                    sql += string.Format(" {0}{1}{2}=@{3},", this.LeftEscapeCharacter, prop.Key, this.RightEscapeCharacter, prop.Key);
                }
                else
                {
                    when += string.Format(" WHERE {0}{1}{2}=@{3}", this.LeftEscapeCharacter, primaryKey, this.RightEscapeCharacter, primaryKey);
                }
                object val = prop.Value;
                if (val == null)
                {
                    val = DBNull.Value;
                }
                DbParameter parameter = this.CreateParameter();
                parameter.Value = val;
                parameter.ParameterName = string.Format("@{0}", prop.Key);
                args.Add(parameter);
            }
            if (!string.IsNullOrEmpty(whereCast))
            {
                when += string.Format(" AND {0} ", whereCast);
            }
            while (sql.Length > 0 && sql[sql.Length - 1] == ',')
            {
                sql = sql.Remove(sql.Length - 1);
            }
            cmd.CommandText = (sql += when);
            return cmd;
        }

        private DbCommand CreateUpdateImpl(object obj, string fromTable, string primaryKey, string whereCast)
        {
            if (obj == null || string.IsNullOrEmpty(fromTable) || string.IsNullOrEmpty(primaryKey))
            {
                throw new ArgumentException();
            }
            string when = string.Empty, sql = string.Format("UPDATE {0} SET ", fromTable);
            DbCommand cmd = this.CreateCommand();
            DbParameterCollection args = cmd.Parameters;
            PropertyInfo[] props = (obj.GetType()).GetProperties();
            int len = props.Length - 1;
            for (int i = 0; i <= len; i++)
            {
                PropertyInfo prop = props[i];
                if (prop.Name != primaryKey)
                {
                    sql += string.Format(" {0}{1}{2}=@{3},", this.LeftEscapeCharacter, prop.Name, this.RightEscapeCharacter, prop.Name);
                }
                else
                {
                    when += string.Format(" WHERE {0}{1}{2}=@{3}", this.LeftEscapeCharacter, primaryKey, this.RightEscapeCharacter, primaryKey);
                }
                object val = prop.GetValue(obj, null);
                if (val == null)
                {
                    val = DBNull.Value;
                }
                DbParameter parameter = this.CreateParameter();
                parameter.Value = val;
                parameter.ParameterName = string.Format("@{0}", prop.Name);
                args.Add(parameter);
            }
            if (!string.IsNullOrEmpty(whereCast))
            {
                when += string.Format(" AND {0} ", whereCast);
            }
            while (sql.Length > 0 && sql[sql.Length - 1] == ',')
            {
                sql = sql.Remove(sql.Length - 1);
            }
            cmd.CommandText = (sql += when);
            return cmd;
        }

        public virtual DbCommand CreateUpdate(object obj, string fromTable, string primaryKey, string whereCast)
        {
            IDictionary<string, object> d = obj as IDictionary<string, object>;
            if (d != null)
            {
                return this.CreateUpdateImpl(d, fromTable, primaryKey, whereCast);
            }
            IList<KeyValuePair<string, object>> l = obj as IList<KeyValuePair<string, object>>;
            if (l != null)
            {
                return this.CreateUpdateImpl(l, fromTable, primaryKey, whereCast);
            }
            return this.CreateUpdateImpl(obj, fromTable, primaryKey, whereCast);
        }

        public virtual int ExecuteNonQuery(DbCommand command, DbConnection connection)
        {
            if (command == null)
            {
                throw new ArgumentNullException("cmd");
            }
            command.Connection = connection ?? throw new ArgumentNullException("connection");
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            return command.ExecuteNonQuery();
        }

        public virtual object ExecuteScalar(DbCommand command, DbConnection connection)
        {
            if (command == null)
            {
                throw new ArgumentNullException("cmd");
            }
            command.Connection = connection ?? throw new ArgumentNullException("connection");
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            return command.ExecuteScalar();
        }

        public virtual bool InvalidParameter(params string[] args)
        {
            if (args.IsNullOrEmpty<string>())
            {
                return true;
            }
            foreach (string item in args)
            {
                if (item.IndexOf("'") > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public virtual DbParameter[] GetParameters(object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            Type clazz = value.GetType();
            PropertyInfo[] properties = clazz.GetProperties();
            DbParameter[] parameters = new DbParameter[properties.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                PropertyInfo prop = properties[i];
                object obj = prop.GetValue(value, null);
                if (obj == null)
                {
                    obj = DBNull.Value;
                }
                DbParameter parameter = this.CreateParameter();
                parameter.Value = obj;
                parameter.ParameterName = string.Format("@{0}", prop.Name);
                parameters[i] = parameter;
            }
            return parameters;
        }

        public virtual DbParameter[] GetParameters(DbConnection connection, string procedure)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            using (DbCommand cmd = this.CreateCommand())
            {
                cmd.CommandText = procedure;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = connection;
                //
                this.DeriveParameters(cmd); // 探测存储过程参数
                                            //
                DbParameterCollection args = cmd.Parameters;
                DbParameter[] buffer = new DbParameter[args.Count];
                for (int i = 0; i < args.Count; i++) // 交接且设置默认值
                {
                    DbParameter arg = args[i];
                    arg.Value = DBNull.Value;
                    buffer[i] = arg;
                }
                return buffer;
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值