C#连接数据库SQL,并转换成list形式

时间:2021-06-09 13:30:35

web config 配置

<connectionStrings>
    <add name="SQLConnString" connectionString="Data Source=数据库账号;Initial Catalog=数据库;User Id=用户名;password=密码" providerName="System.Data.SqlClient" />
   </connectionStrings>  

 

string connectionString = ConfigurationManager.ConnectionStrings["SQLConnString"].ToString();//连接字符串
                SqlConnection cn = new SqlConnection(connectionString);//数据库连接
                string sql = "select cameraId,cameraName,cameraNo,defence,deviceId,deviceName,deviceSerial,isEncrypt,isShared,picUrl,status,videoLevel from Video";
                var dataset = Query(sql, connectionString);

                var lstVideo = DataSetToIList<camera.VideoList>(dataset, 0);

 

 /// <summary>    
        /// 执行查询语句,返回DataSet    
        /// </summary>    
        /// <param name="SQLString">查询语句</param>    
        /// <returns>DataSet</returns>    
        public static DataSet Query(string SQLString, string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    throw new Exception(E.Message);
                    //   ITNB.Base.Error.showError(E.Message.ToString());    
                }
                return ds;
            }
        }


        /// <summary> 
        /// DataSet装换为泛型集合 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="p_DataSet">DataSet</param> 
        /// <param name="p_TableIndex">待转换数据表索引</param> 
        /// <returns></returns> 
        public static List<T> DataSetToIList<T>(DataSet p_DataSet, int p_TableIndex)
        {
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (p_TableIndex > p_DataSet.Tables.Count - 1)
                return null;
            if (p_TableIndex < 0)
                p_TableIndex = 0;

            DataTable p_Data = p_DataSet.Tables[p_TableIndex];
            // 返回值初始化 
            List<T> result = new List<T>();
            for (int j = 0; j < p_Data.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < p_Data.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值 (枚举类型无法转换,单独拎出来)
                        if (pi.Name.Equals(p_Data.Columns[i].ColumnName))
                        { 
                            // 数据库NULL值单独处理 
                            if (p_Data.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, p_Data.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }