最基礎的ADO.NET 和 DataTable轉Json
阿新 • • 發佈:2018-11-10
ADO.NET
public static class SqlHelper { public static string ConStr { get; set; } = string.Empty; /// <summary> /// 執行一條語句 /// </summary> /// <param name="cmd">cmd物件</param> /// <param name="error">錯誤資訊</param> /// <returns>受影響行數</returns> public static int ExecuteNonQuery(SqlCommand cmd, out string error) { using (var con = new SqlConnection(ConStr)) { cmd.Connection = con; try { cmd.Connection.Open(); var changeCount = cmd.ExecuteNonQuery(); error = string.Empty; return changeCount; } catch (Exception e) { cmd.Connection.Close(); cmd.Dispose(); error = e.Message; return 0; } } } /// <summary> /// 執行一條語句 /// </summary> /// <param name="cmd">cmd物件</param> /// <param name="cmdType">操作型別是儲存過程還是sql語句</param> /// <param name="error">錯誤資訊</param> /// <returns>受影響行數</returns> public static int ExecuteNonQuery(SqlCommand cmd, CommandType cmdType, out string error) { using (var con = new SqlConnection(ConStr)) { cmd.Connection = con; try { cmd.Connection.Open(); cmd.CommandType = cmdType; var changeCount = cmd.ExecuteNonQuery(); error = string.Empty; return changeCount; } catch (Exception e) { cmd.Connection.Close(); cmd.Dispose(); error = e.Message; return 0; } } } /// <summary> /// 執行一條語句,開啟事務 /// </summary> /// <param name="cmd">cmd物件</param> /// <param name="cmdType">操作型別是儲存過程還是sql語句</param> /// <param name="trans">事物物件</param> /// <param name="error">錯誤資訊</param> /// <returns>受影響行數</returns> public static int ExecuteNonQuery(SqlCommand cmd, CommandType cmdType, ref SqlTransaction trans, out string error) { using (var con = new SqlConnection(ConStr)) { cmd.Connection = con; try { cmd.Connection.Open(); trans = trans ?? cmd.Connection.BeginTransaction(); cmd.Transaction = trans; cmd.CommandType = cmdType; var changeCount = cmd.ExecuteNonQuery(); error = string.Empty; return changeCount; } catch (Exception e) { cmd.Connection.Close(); cmd.Dispose(); error = e.Message; return 0; } } } /// <summary> /// 返回查詢結果的第一列第一行 /// </summary> /// <param name="cmd">cmd物件</param> /// <param name="error">錯誤資訊</param> /// <returns>返回值</returns> public static string ExecuteScalar(SqlCommand cmd, out string error) { using (var con = new SqlConnection(ConStr)) { cmd.Connection = con; try { cmd.Connection.Open(); var obj = cmd.ExecuteScalar(); error = string.Empty; return obj.ToString(); } catch (Exception e) { cmd.Connection.Close(); cmd.Dispose(); error = e.Message; return string.Empty; } } } /// <summary> /// 返回 datatable格式的查詢結果,有異常會返回 null /// </summary> /// <param name="cmd">cmd物件</param> /// <param name="error">錯誤資訊</param> /// <returns>datatable格式</returns> public static DataTable ExecuteAdapter(SqlCommand cmd, out string error) { using (var con = new SqlConnection(ConStr)) { cmd.Connection = con; try { cmd.Connection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dataTable = new DataTable(); error = string.Empty; return dataTable; } catch (Exception e) { cmd.Connection.Close(); cmd.Dispose(); error = e.Message; return null; } } } }
DataTable 轉JSON字串 和DataTable 轉 匿名類陣列 可支援 Lamda Link 有 智慧提示
public static class JsonHelper { /// <summary> /// 轉換物件時,是否大寫小寫或者不設定 /// </summary> public enum ToJsonFieldCaseEnums { None = 0, ToUpper = 1, ToLower } /// <summary> /// DsataTale 轉換為JSON字串, 使用包 Newtonsoft.Json來序列化生成的List達成目的 /// </summary> /// <param name="table">Datatable物件</param> /// <returns>JSON字串</returns> public static string DataTableToJson(this DataTable table) { return DataTableToJson(table, null, ToJsonFieldCaseEnums.None); } /// <summary> /// DsataTale 轉換為JSON字串, 使用包 Newtonsoft.Json來序列化生成的List達成目的 /// </summary> /// <param name="table">Datatable物件</param> /// <param name="fieldCase">大小寫轉換或者 none 不轉換 </param> /// <returns>JSON字串</returns> public static string DataTableToJson(this DataTable table, ToJsonFieldCaseEnums fieldCase = ToJsonFieldCaseEnums.None) { return DataTableToJson(table, null, fieldCase); } /// <summary> /// DsataTale 轉換為JSON字串, 使用包 Newtonsoft.Json來序列化生成的List達成目的 /// </summary> /// <param name="table">Datatable物件</param> /// <param name="fieldMap">對應字典,會替換掉Datatable中的列頭 舊,新 </param> /// <param name="fieldCase">大小寫轉換或者 none 不轉換 </param> /// <returns>JSON字串</returns> public static string DataTableToJson(this DataTable table, Dictionary<string, string> fieldMap, ToJsonFieldCaseEnums fieldCase = ToJsonFieldCaseEnums.None) { if (table == null) return null; if (fieldCase != ToJsonFieldCaseEnums.None) { for (int i = 0; i < table.Columns.Count; i++) { if (fieldCase == ToJsonFieldCaseEnums.ToUpper) { table.Columns[i].ColumnName = table.Columns[i].ColumnName.ToUpper(); } else { table.Columns[i].ColumnName = table.Columns[i].ColumnName.ToLower(); } } } if (fieldMap != null && fieldMap.Count > 0) { foreach (var item in fieldMap) { if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value)) { if (table.Columns.Contains(item.Key)) { table.Columns[item.Key].ColumnName = item.Value; } } } } string tmpStr = table.ToJson(); return tmpStr; } /// <summary> /// Jin 20180804 將DATATABLE轉成匿名JSON物件列表 /// 將Json字串反序列化為匿名型別,可以支援Lamda表示式,Link表示式,但是必須傳入匿名型別的結構 FormateObj /// 使用示例 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }} var data = DataTable例項物件.DataTableToJsonList(formatObj) /// </summary> /// <typeparam name="T">泛型如果是物件就傳入new{name = string.empty,age = 18, isFriend = true } 陣列格式:new[]{{name = string.empty,age = 18, isFriend = true }}</typeparam> /// <param name="table">DataTable物件</param> /// <param name="formatObj">結構物件,反序列化的匿名類屬性將會以此為準例如 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }}</param> /// <returns>匿名型別的物件,支援Lamda,Link,可以智慧提示屬性</returns> public static T DataTableToJsonList<T>(this DataTable table, T formatObj) { return DataTableToJsonList(table, formatObj, null, ToJsonFieldCaseEnums.None); } /// <summary> /// Jin 20180804 將DATATABLE轉成匿名JSON物件列表 /// 將Json字串反序列化為匿名型別,可以支援Lamda表示式,Link表示式,但是必須傳入匿名型別的結構 FormateObj /// 使用示例 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }} var data = DataTable例項物件.DataTableToJsonList(formatObj) /// </summary> /// <typeparam name="T">泛型如果是物件就傳入new{name = string.empty,age = 18, isFriend = true } 陣列格式:new[]{{name = string.empty,age = 18, isFriend = true }}</typeparam> /// <param name="table">DataTable物件</param> /// <param name="formatObj">結構物件,反序列化的匿名類屬性將會以此為準例如 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }}</param> /// <param name="fieldCase">屬性名稱大小寫控制</param> /// <returns>匿名型別的物件,支援Lamda,Link,可以智慧提示屬性</returns> public static T DataTableToJsonList<T>(this DataTable table, T formatObj, ToJsonFieldCaseEnums fieldCase = ToJsonFieldCaseEnums.None) { return DataTableToJsonList(table, formatObj, null, fieldCase); } /// <summary> /// Jin 20180804 將DATATABLE轉成匿名JSON物件列表 /// 將Json字串反序列化為匿名型別,可以支援Lamda表示式,Link表示式,但是必須傳入匿名型別的結構 FormateObj /// 使用示例 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }} var data = DataTable例項物件.DataTableToJsonList(formatObj) /// </summary> /// <typeparam name="T">泛型如果是物件就傳入new{name = string.empty,age = 18, isFriend = true } 陣列格式:new[]{{name = string.empty,age = 18, isFriend = true }}</typeparam> /// <param name="table">DataTable物件</param> /// <param name="formatObj">結構物件,反序列化的匿名類屬性將會以此為準例如 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }}</param> /// <param name="fieldMap">屬性對映表</param> /// <param name="fieldCase">屬性名稱大小寫控制</param> /// <returns>匿名型別的物件,支援Lamda,Link,可以智慧提示屬性</returns> public static T DataTableToJsonList<T>(this DataTable table, T formatObj, Dictionary<string, string> fieldMap, ToJsonFieldCaseEnums fieldCase = ToJsonFieldCaseEnums.None) { if (table == null) return default(T); if (fieldCase != ToJsonFieldCaseEnums.None) { for (int i = 0; i < table.Columns.Count; i++) { if (fieldCase == ToJsonFieldCaseEnums.ToUpper) { table.Columns[i].ColumnName = table.Columns[i].ColumnName.ToUpper(); } else { table.Columns[i].ColumnName = table.Columns[i].ColumnName.ToLower(); } } } if (fieldMap != null && fieldMap.Count > 0) { foreach (var item in fieldMap) { if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value)) { if (table.Columns.Contains(item.Key)) { table.Columns[item.Key].ColumnName = item.Value; } } } } string tmpStr = table.ToJson(); if (string.IsNullOrWhiteSpace(tmpStr)) { return default(T); } return tmpStr.ToList(formatObj); } /// <summary> /// 將Json字串反序列化為匿名型別,可以支援Lamda表示式,Link表示式,但是必須傳入匿名型別的結構 FormateObj /// 使用示例 var formatObj = new[]{{name = string.empty,age = 18, isFriend = true }} var data = DataTable例項物件.DataTableToJsonList(formatObj) /// </summary> /// <typeparam name="T">泛型如果是物件就傳入new{name = string.empty,age = 18, isFriend = true } 陣列格式:new[]{{name = string.empty,age = 18, isFriend = true }}</typeparam> /// <param name="jsonStr">Json字串</param> /// <param name="formatObj">匿名型別結構物件</param> /// <returns>支援Lamda,Link表示式的匿名物件,可以智慧提示屬性</returns> public static T ToList<T>(this string jsonStr, T formatObj) { return string.IsNullOrEmpty(jsonStr) ? default(T) : JsonConvert.DeserializeAnonymousType(jsonStr, formatObj); } /// <summary> /// 序列化 /// </summary> /// <param name="obj">序列化物件</param> /// <returns>返回JSON字串</returns> public static string ToJson(this object obj) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; var numConverter = new JsonNumberConverter(); return JsonConvert.SerializeObject(obj, timeConverter, numConverter); } }