数据库
首页 > 数据库> > SqlQueryDynamic

SqlQueryDynamic

作者:互联网

 

SqlQueryDynamic
 //调用
            //dynamic dy = PubUtils.SqlQueryDynamic("SELECT * FROM User_Permission");           
            //var upJson = JsonConvert.SerializeObject(dy);
            //var orders = JsonConvert.DeserializeObject<List<SystemManage.UserPermissionModel>>(upJson);

 

public static IEnumerable<dynamic> SqlQueryDynamic(string Sql,params SqlParameter[] parameters)
        {
            string ConnStr = "";
            SqlConnection sqlconn = new SqlConnection(ConnStr == "" ? PubUtils.ConnStr : ConnStr);           
            using (var cmd = sqlconn.CreateCommand())
            {
                cmd.CommandText = Sql;
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                foreach (var p in parameters)
                {
                    var dbParameter = cmd.CreateParameter();
                    dbParameter.DbType = p.DbType;
                    dbParameter.ParameterName = p.ParameterName;
                    dbParameter.Value = p.Value;
                    cmd.Parameters.Add(dbParameter);
                }

                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        var row = new ExpandoObject() as IDictionary<string, object>;
                        for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++)
                        {
                            row.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]);
                        }
                        yield return row;
                    }
                }
            }
        }

 

标签:dataReader,dbParameter,fieldCount,cmd,var,SqlQueryDynamic
来源: https://www.cnblogs.com/Tonyyang/p/16478002.html