web config 配置web
<connectionStrings>
<add name="SQLConnString" connectionString="Data Source=數據庫帳號;Initial Catalog=數據庫;User Id=用戶名;password=密碼" providerName="System.Data.SqlClient" />
</connectionStrings> sql
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);ide
/// <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; }