Simple operation based on the reflection characteristics of the database

First, on a SqlHelper

public class SqlHelper
    {
        public static string GetSqlConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["State"].ConnectionString;
        }
       
        public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(GetSqlConnectionString()))
            {
                using (SqlCommand comm = conn.CreateCommand())
                {
                    conn.Open();
                    comm.CommandText = sql;
                    comm.Parameters.AddRange(parameters);
                    return comm.ExecuteNonQuery();
                }
            }
        }
       
        public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(GetSqlConnectionString()))
            {
                using (SqlCommand comm = conn.CreateCommand())
                {
                    conn.Open();
                    comm.CommandText = sql;
                    comm.Parameters.AddRange(parameters);
                    return comm.ExecuteScalar();
                }
            }
        }
        
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, GetSqlConnectionString()))
            {
                DataTable dt = new DataTable();
                adapter.SelectCommand.Parameters.AddRange(parameters);
                adapter.Fill (dt); 
                return dt; 
            } 
        } 

        public static the SqlDataReader the ExecuteReader ( String sqlText, the params the SqlParameter [] Parameters) 
        { 
            // the SqlDataReader requirements, when it has read data, it its exclusive SqlConnection object, and must be SqlConnection open state of 
            the SqlConnection Conn = new new the SqlConnection (GetSqlConnectionString ()); // Do not release the connection, since the latter also need to connect open 
            the SqlCommand cmd = conn.CreateCommand (); 
            conn.Open (); 
            cmd.CommandText = sqlText; 
            cmd.Parameters .AddRange (the Parameters); 
            //CommandBehavior.CloseConnection SqlDataReader when released, the way the objects are also freed SqlConnection 
            return cmd.ExecuteReader (CommandBehavior.CloseConnection); 
        } 
    }
View Code

 

While the database link configuration profiles written

 <connectionStrings>
    <add name="State" connectionString="server=.;user id=sa;pwd=;database=xxx"/>
  </connectionStrings>

The BaseModel also add good

 public class BaseModel
    {
        public int ID { get; set; }

        public static IEnumerable<T> Find<T>() where T : class, new()
        {
            List<T> result = new List<T>();

            List<string> list = new List<string>();
            Type type = typeof(T);

            PropertyInfo[] propertyInfo = type.GetProperties();
            foreach (var item in propertyInfo)
            {
                list.Add(item.Name);
            }
            string cloStr = string.Join(",", list);

            var conStr = ConfigurationManager.ConnectionStrings["State"].ConnectionString;
            string sql = "select " + cloStr + " from dbo.[" + type.Name + "]";

            SqlDataReader read = SqlHelper.ExecuteReader(sql);

            while (read.Read())
            {
                T model = Activator.CreateInstance<T>();
                for (int i = 0; i < read.FieldCount; i++)
                {
                    PropertyInfo pi = type.GetProperty(read.GetName(i));
                    pi.SetValue(model, read.GetValue(i));
                }

                result.Add(model);
            }

            return result;
        }

        public static bool Insert<T>(T t)
        {
            bool result = false;

            Type type = typeof(T);
            

            StringBuilder sql = new StringBuilder();
            sql.Append("Insert into dbo.[" + type.Name + "]");
            sql.Append("(" + GetColmons(t) + ")");
            sql.Append(" values(" + GetValues<T>(t) + ")");
            result = SqlHelper.ExecuteNonQuery(sql.ToString()) > 0;

            return result;
        }

        public static bool Delete<T>(int id)
        {
            bool result = false;
            try
            {
                Type type = typeof(T);
                StringBuilder sql = new StringBuilder();
                sql.Append("Delete dbo.[" + type.Name+"]");
                sql.Append(" where id=" + id);
                result = SqlHelper.ExecuteNonQuery(sql.ToString()) > 0;
            }
            catch
            {

            }

            return result;
        }

        public static string GetValues<T>(T t)
        {
            if (t == null)
            {
                return string.Empty;
            }

            return string.Join(",",
                t.GetType().GetRuntimeProperties().Select(p => string.Format("'{0}'", p.GetValue(t))).ToArray());

        }

        private static string GetColmons<T>(T t)
        {
            if (t == null)
            {
                return string.Empty;
            }

            return string.Join(",", t.GetType().GetProperties().Select(p => p.Name).ToArray());
        }
    }
View Code

 

Add the following to do a test Model

 public class User:BaseModel
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public long Phone { get; set; }
    }
View Code

Then the upper Code

static void Main(string[] args)
        {
            Console.WriteLine("====Start=====");
            


            User user = new User();
            
            user.ID = 5;
            user.Name = "邹邹";
            user.Age = 18;
            user.Phone = 123123;

            bool _insertUser = BaseModel.Insert<User>(user);

            bool _delUser = BaseModel.Delete<User>(5);

            var _userList BaseModel.Find = <the User> ();
             IF (_insertUser) 
            { 
                Console.WriteLine ( " insert successfully " ); 
            } 
            the else 
            { 
                Console.WriteLine ( " insert successfully " ); 
            } 
            IF (_delUser) 
            { 
                Console.WriteLine ( " deleted successfully " ); 
            } 
            the else 
            { 
                Console.WriteLine ( " deletion failed " ); 
            }

            foreach ( var Item in _userList) 
            { 
                Console.WriteLine ($ " ID: {} item.id - name {item.Name} - Age: {item.Age} - phone number: {item.Phone} " ); 
            } 

            Console .ReadKey (); 
        }
View Code

 

Success ~ ~

 

Guess you like

Origin www.cnblogs.com/zousc/p/11222208.html