ORM小練習代碼

 

DOG類mysql

namespace RupengORM
{
    public class Dog
    {
        public Dog()
        {
        }

        /// <summary>
        ///     顯示提供無參構造函數
        /// </summary>
        /// <param name="aa"></param>
        public Dog(int aa)
        {
        }

        public int Id { get; set; }

        public string Name { get; set; }

        public int Weight { set; get; }
    }
}

Sqlhelper:sql

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

namespace RupengORM
{
    public class DbSqlhelper
    {
        private static readonly string Sqlconnstr = ConfigurationManager.ConnectionStrings["mysqlconn"].ConnectionString;

        public static MySqlConnection CreateConnection()
        {
            MySqlConnection conn = new MySqlConnection(Sqlconnstr);
            conn.Open();
            return conn;
        }

        public static int ExecuteNonQuery(MySqlConnection conn, string sql, params MySqlParameter[] parameters)
        {
            using (MySqlCommand cmd=conn.CreateCommand())
            {
                cmd.CommandText = sql;
                 cmd.Parameters.AddRange(parameters);
                
                return   cmd.ExecuteNonQuery();
            }
        }

        public static int ExecuteNonQuery(string sql, params MySqlParameter [] parameters)
        {
            using (MySqlConnection conn = CreateConnection())
            {
                return ExecuteNonQuery(conn, sql, parameters);


            }
        }

        public static object ExecuteScalar(MySqlConnection conn, string sql, Dictionary<string, object> dictionary)
        {
            using (MySqlCommand cmd=conn.CreateCommand())
            {
                cmd.CommandText = sql;
                foreach (var kvp in dictionary)
                {
                    IDbDataParameter parameter = cmd.CreateParameter();
                    parameter.ParameterName = kvp.Key;
                    parameter.Value = kvp.Value;
                    cmd.Parameters.Add(parameter);
                }
                return cmd.ExecuteScalar();

            }
            
        }

        public static object ExecuteScalar(string sql, Dictionary<string, object> dictionary)
        {
            using (MySqlConnection conn=CreateConnection())
            {
                return ExecuteScalar(conn, sql, dictionary);
            }
        }

        public static DataTable ExecuteQuery(MySqlConnection conn, string sql, Dictionary<string, object> dictionary)
        {
            DataTable dataTable=new DataTable();
            using (MySqlCommand cmd=conn.CreateCommand())
            {
                cmd.CommandText = sql;
                foreach (var kvp in dictionary)
                {
                    IDbDataParameter parameter = cmd.CreateParameter();
                    parameter.ParameterName = kvp.Key;
                    parameter.Value = kvp.Value;
                    cmd.Parameters.Add(parameter);
                    using (IDataReader reader=cmd.ExecuteReader())
                    {
                        dataTable.Load(reader);
                    }

                }
            }

            return dataTable;
        }

        public static DataTable ExecuteQuery(  string sql, Dictionary<string, object> dictionary)
        {
            using (MySqlConnection conn=CreateConnection())
            {
                return ExecuteQuery(conn, sql, dictionary);
            }
        }




    }

    
}

RProm 實現過程:數據庫

using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;

namespace RupengORM
{
    internal class RPorm
    {
        //約定:一、類名要和表名同樣
        //二、字段名和數據庫列名同樣
        //三、主鍵的名字必須叫Id,必須是自動遞增,int類型
        //
        //
        //
        //
        //
        public static void Insert(object obj)
        {
            //得到obj對象的類名
            var type = obj.GetType(); //typeof(Person)
            var className = type.Name; //類名:Person
            //propertyInfos得到類裏面全部的屬性
            var propertyInfos = type.GetProperties();
            var propNames = new string[propertyInfos.Length - 1]; //排除掉Id
            var paramNames = new string[propertyInfos.Length - 1];
            var sqlParameters = new MySqlParameter[propertyInfos.Length - 1];
            //    Dictionary<string, object>  dic = new Dictionary<string, object>();
            var count = 0;
            foreach (var propInfo in propertyInfos)
            {
                var propName = propInfo.Name;

                if (propName != "Id") //排除Id
                {
                    //遍歷賦值,包含ID不進入賦值
                    propNames[count] = propName;
                    paramNames[count] = "@" + propName;
                    var mySqlParameter = new MySqlParameter();
                    mySqlParameter.ParameterName = "@" + propName;
                    mySqlParameter.Value = propInfo.GetValue(obj); //去obj對象屬性的值
                    sqlParameters[count] = mySqlParameter;
                    count++;
                }
            }


            //拼接生成insert語句
            var sbSql = new StringBuilder();

            sbSql.Append("insert into ")
                .Append(className)
                .Append("(")
                .Append(string.Join(",", propNames))
                .Append(")");
            sbSql.Append(" values (").Append(string.Join(",", paramNames)).Append(")");


            DbSqlhelper.ExecuteNonQuery(sbSql.ToString(), sqlParameters); //params可變長度參數本質上就是一個數組
        }

        public static object SelectById(Type type, int id)
        {
            //將表名獲取到
            var classname = type.Name;

            var sql = "select * from " + classname + " where id=@id";
            var dictionary = new Dictionary<string, object>();
            dictionary["@id"] = id;
            var dataTable = DbSqlhelper.ExecuteQuery(sql, dictionary);

            if (dataTable.Rows.Count <= 0)
            {
                return null;
            }
            if (dataTable.Rows.Count > 1)
            {
                throw new Exception("查到多條ID=" + id + "的數據");
            }
            var row = dataTable.Rows[0];
            //建立type類的一個對象
            var obj = Activator.CreateInstance(type);

            //給obj對象的每個屬性(包括Id)賦值,獲得id name weight
            foreach (var propInfo in type.GetProperties())
            {
                var propName = propInfo.Name; //屬性名就是別名

                var value = row[propName]; //獲取數據庫中列的值

                propInfo.SetValue(obj, value); //給obj對象的propinfo屬性賦值爲value
            }
            return obj;
        }

        public static T SelectById<T>(int id) where T : new() //泛型約束,約束T必須有一個無參的構造函數
        {
            var type = typeof (T); //typeof(Person)

            var classname = type.Name;

            var sql = "select * from " + classname + " where id=@id";
            var dictionary = new Dictionary<string, object>();
            dictionary["@id"] = id;
            var dataTable = DbSqlhelper.ExecuteQuery(sql, dictionary);


            if (dataTable.Rows.Count <= 0)
            {
                return default(T); //default(T)運算符用來得到類型的默認值
                //default(int)→0 default(bool)→false default(Person)→null
            }
            if (dataTable.Rows.Count > 1)
            {
                throw new Exception("查到多條ID=" + id + "的數據");
            }
            var row = dataTable.Rows[0];
            //建立type類的一個對象
            //   var obj = Activator.CreateInstance(type);
            var obj = new T(); //泛型約束

            //給obj對象的每個屬性(包括Id)賦值 返回當前 Type 的全部公共屬性。
            foreach (var propInfo in type.GetProperties())
            {
                var propName = propInfo.Name; //屬性名就是別名

                var value = row[propName]; //獲取數據庫中列的值

                propInfo.SetValue(obj, value); //給obj對象的propinfo屬性賦值爲value
            }
            return obj;
        }

        public static bool DeleteById(Type type, int id)
        {
            var classname = type.Name;

            var sql = "delete from " + classname + " where id=@id ";
            var i = DbSqlhelper.ExecuteNonQuery(sql, new MySqlParameter {ParameterName = "@id", Value = id});
            //delete from dog where name='孔老二4'    
            return i > 0;
        }

        public static bool UpdateById(object obj)
        {
            var type = obj.GetType();

            var classname = type.Name; //得到表名

            var propertyInfos = type.GetProperties(); //得到表名中的功能屬性
            var propNames = new string[propertyInfos.Length]; //獲取該屬性的長度
            var paramNames = new string[propertyInfos.Length];
            var sqlParameters = new MySqlParameter[propertyInfos.Length];
            var count = 0;
            foreach (var propInfo in propertyInfos)
            {
                var propName = propInfo.Name;
                var mySqlParameter = new MySqlParameter();
                mySqlParameter.ParameterName = "@" + propName;
                mySqlParameter.Value = propInfo.GetValue(obj); //去obj對象屬性的值
                sqlParameters[count] = mySqlParameter;

                if (propName != "Id") //排除Id
                {
                    //遍歷賦值,包含ID不進入賦值
                    propNames[count] = propName; //name

                    paramNames[count] = propName + "=@" + propName; //@name
                }
                count++;
            }
            var oop = string.Join("  ,  ", paramNames).Substring(4);
            // sqlParameters;
            var sb = new StringBuilder();
            sb.Append("update ").Append(classname).Append(" set ").Append(oop).Append(" where id=@id");
              var sqltxt = sb.ToString();
            var i = DbSqlhelper.ExecuteNonQuery(sqltxt, sqlParameters);
            //生成update語句
            //update dog set name=@name weight=@weight where id=@id
            //怎麼知道那一列被修改了呢
            //把全部列都更新一下。反正不變的仍是不變

            return i > 0;
        }
    }
}

 

 

 

主程序:數組

using System;

namespace RupengORM
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //ORM:EF(entity framework,Dapper,Nhibernate)
            // Person p1=new Person();
            // p1.Name = "rupeng";
            // p1.Age = 7;
            // RPorm.Insert(p1);


            for (var i = 0; i < 10; i++)
            {
                var d1 = new Dog();
                d1.Name = "孔老二" + i;
                d1.Weight = 30;
                RPorm.Insert(d1);
            }


            //Person p1 = (Person)RPorm.SelectById(typeof(Person),1);
            //Console.WriteLine(p1.Name+"的年齡是"+p1.Age);

            //   Dog p2 = (Dog)RPorm.SelectById(typeof(Dog), 1);
            //if (p2 == null)
            //{
            //    Console.WriteLine("沒找到狗");
            //}
            //else
            //{
            //    Console.WriteLine(p2.Name);
            //}

            //Dog dog = RPorm.SelectById<Dog>(1);

            //Console.WriteLine(dog.Name);
            //  Type type = new Type typeof(Dog);

            //bool aa=    RPorm.DeleteById(typeof(Dog),2);
            //Console.WriteLine(aa);
            var dog = new Dog();
            dog.Weight++;
            dog.Name = "孔老二";
            dog.Id = 9;
            var update = RPorm.UpdateById(dog);


            Console.WriteLine(update);
            Console.ReadKey();
        }
    }
}
相關文章
相關標籤/搜索