博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
简单的sql server->bs或cs数据交互模式
阅读量:6547 次
发布时间:2019-06-24

本文共 22165 字,大约阅读时间需要 73 分钟。

主要记录工作当中遇到的一些问题和总结的一些经验

客户端请求-->web服务接口-->sql 语句执行(存储在数据库中)-->web服务(客户端通过调用web服务接口)-->返回DataTable或Dataset(sql server)--> 统一的DataTable或Dataset转换成对象-->提交给客户端(xml、json等等其他的)

1、首先通过sql语句返回结果,返回的结果一般都以Dataset的形式和DataTable的形式返回。

2、统一的DataTable或Dataset转换成对象

1 #region 写对象信息  2   3         ///   4         ///   5         ///   6         /// 
7 /// 8 ///
9 public T WriteTObjectInfo
(string tableName, DataRow dr, string[] exceptArray) 10 { 11 try 12 { 13 if (this.Status == 0) 14 { 15 throw new Exception(this.Msg); 16 } 17 18 T item = Activator.CreateInstance
(); 19 20 List
listParameter = GetProperties
(item, exceptArray); 21 22 foreach (Parameter p in listParameter) 23 { 24 foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns) 25 { 26 if (dc.ColumnName == p.Name) 27 { 28 Type type = item.GetType(); 29 30 MethodInfo method = type.GetMethod("SetAttributeValue"); 31 32 method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() }); 33 } 34 } 35 } 36 37 return item; 38 } 39 catch (Exception ex) 40 { 41 throw new Exception("写" + Activator.CreateInstance
().ToString() + "信息发生错误,错误原因:" + ex.Message); 42 } 43 } 44 45 ///
46 /// 47 /// 48 ///
49 ///
50 ///
51 public T WriteTObjectInfo
(string tableName) 52 { 53 try 54 { 55 if (this.Status == 0) 56 { 57 throw new Exception(this.Msg); 58 } 59 60 T item = Activator.CreateInstance
(); 61 62 if (this.dsResult.Tables.Contains(tableName)) 63 { 64 DataRow dr = this.dsResult.Tables[tableName].Rows[0]; 65 66 List
listParameter = GetProperties
(item); 67 68 foreach (Parameter p in listParameter) 69 { 70 foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns) 71 { 72 if (dc.ColumnName == p.Name) 73 { 74 Type type = item.GetType(); 75 76 MethodInfo method = type.GetMethod("SetAttributeValue"); 77 78 method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() }); 79 } 80 } 81 } 82 } 83 84 return item; 85 } 86 catch (Exception ex) 87 { 88 throw new Exception("写" + Activator.CreateInstance
() + "信息发生错误,错误原因:" + ex.Message); 89 } 90 } 91 92 ///
93 /// 94 /// 95 ///
96 ///
97 ///
98 public T WriteTObjectInfo
(string tableName, string[] exceptArray) 99 {100 try101 {102 if (this.Status == 0)103 {104 throw new Exception(this.Msg);105 }106 107 T item = Activator.CreateInstance
();108 109 if (this.dsResult.Tables.Contains(tableName))110 {111 DataRow dr = this.dsResult.Tables[tableName].Rows[0];112 113 List
listParameter = GetProperties
(item, exceptArray);114 115 foreach (Parameter p in listParameter)116 {117 foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)118 {119 if (dc.ColumnName == p.Name)120 {121 Type type = item.GetType();122 123 MethodInfo method = type.GetMethod("SetAttributeValue");124 125 method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });126 }127 }128 }129 }130 131 return item;132 }133 catch (Exception ex)134 {135 throw new Exception("写" + Activator.CreateInstance
() + "信息发生错误,错误原因:" + ex.Message);136 }137 }138 139 ///
140 /// 141 /// 142 ///
143 ///
144 ///
145 public List
WriteTObjectInfoList
(string tableName, string[] exceptArray)146 {147 try148 {149 if (this.Status == 0)150 {151 throw new Exception(this.Msg);152 }153 154 List
list = new List
();155 156 if (this.dsResult.Tables.Contains(tableName))157 {158 foreach (DataRow dr in this.dsResult.Tables[tableName].Rows)159 {160 T item = WriteTObjectInfo
(tableName, dr, exceptArray);161 162 list.Add(item);163 }164 }165 166 return list;167 }168 catch (Exception ex)169 {170 throw new Exception("写" + Activator.CreateInstance
().ToString() + "信息发生错误,错误原因:" + ex.Message);171 }172 }173 174 ///
175 /// 176 /// 177 ///
178 ///
179 ///
180 public List
WriteTObjectInfoList
(string tableName)181 {182 return WriteTObjectInfoList
(tableName, new string[] { });183 }184 185 #endregion
View Code

  以上代码统一用泛型实现

比较实用的获取属性的代码

1 ///   2         /// 获取对象的属性名称、值和描述  3         ///   4         /// 
对象的类型
5 /// 对象 6 ///
对象列表
7 public List
GetProperties
(T t) 8 { 9 List
list = new List
(); 10 11 if (t == null) 12 { 13 return list; 14 } 15 PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); 16 17 if (properties.Length <= 0) 18 { 19 return list; 20 } 21 foreach (PropertyInfo item in properties) 22 { 23 string name = item.Name; //名称 24 object value = item.GetValue(t, null); //值 25 26 string des = string.Empty; 27 28 try 29 { 30 des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值 31 } 32 catch { } 33 34 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) 35 { 36 Parameter parameter = new Parameter(); 37 38 parameter.Name = name; 39 parameter.Value = value == null ? "" : value.ToString(); 40 parameter.Object = des; 41 42 list.Add(parameter); 43 } 44 else 45 { 46 GetProperties(value); 47 } 48 } 49 return list; 50 } 51 52 ///
53 /// 54 /// 55 ///
56 ///
57 ///
58 ///
59 public List
GetProperties
(T t, string[] exceptArray) 60 { 61 List
list = new List
(); 62 63 if (t == null) 64 { 65 return list; 66 } 67 PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); 68 69 if (properties.Length <= 0) 70 { 71 return list; 72 } 73 foreach (PropertyInfo item in properties) 74 { 75 string name = item.Name; //名称 76 object value = item.GetValue(t, null); //值 77 string des = string.Empty; 78 79 try 80 { 81 des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值 82 } 83 catch (Exception ex) 84 { 85 des = string.Empty; 86 } 87 88 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) 89 { 90 if (!((IList)exceptArray).Contains(name)) 91 { 92 Parameter parameter = new Parameter(); 93 94 parameter.Name = name; 95 parameter.Value = value == null ? "" : value.ToString(); 96 parameter.Object = des; 97 98 list.Add(parameter); 99 }100 }101 else102 {103 GetProperties(value);104 }105 }106 return list;107 }
View Code

    基础的Parameter类

1 public class Parameter 2     { 3         ///  4         /// 名称 5         ///  6         private string _name = string.Empty; 7  8         ///  9         /// 获取或设置名称10         /// 11         public string Name12         {13             get { return this._name; }14             set { this._name = value; }15         }16 17         /// 18         /// 值19         /// 20         private string _value = string.Empty;21 22         /// 23         /// 获取或设置值24         /// 25         public string Value26         {27             get { return this._value; }28             set { this._value = value; }29         }30 31         private object _object = null;32 33 34         public object Object35         {36             get { return this._object; }37             set { this._object = value; }38         }39 40         /// 41         /// 构造函数42         /// 43         /// 名称44         /// 值45         public Parameter(string name, string value)46         {47             this.Name = name;48             this.Value = value;49         }50 51         public Parameter(string name, object obj)52         {53             this.Name = name;54             this.Object = obj;55         }56 57         /// 58         /// 构造函数59         /// 60         public Parameter()61         {62 63         }64 65         /// 66         /// 67         /// 68         /// 
69 public override string ToString()70 {71 return string.Format(@"名称(Name):{0},值(Value):{1},对象(Object):{2}", this.Name, this.Value, this.Object);72 }73 }
View Code

    对象例子(这个对象例子的类,这个类其实和上面的DataTable和Dataset是对应的,通过以上的操作可以把DataTable或Dataset转换成具体的对象),因为这个类是比较统一的可以用代码生成工具可以直接生成

1 public class Log  2     {  3         #region 属性  4   5         [Description("数据日志编号")]  6         public string LogID { get; set; }  7   8         [Description("设备编号")]  9         public string DeviceID { get; set; } 10  11         [Description("设备名称")] 12         public string DeviceName { get; set; } 13  14         [Description("质控项目编号")] 15         public string QCItemDicID { get; set; } 16  17         [Description("质控项目中文名称")] 18         public string CNName { get; set; } 19  20         [Description("质控项目英文名称")] 21         public string ENName { get; set; } 22  23         [Description("质控项目名称简拼码")] 24         public string JPM { get; set; } 25  26         [Description("质控项目名称简拼码")] 27         public string NameAB { get; set; } 28  29         [Description("质控项目单位")] 30         public string Unit { get; set; } 31  32         [Description("设备质控编号")] 33         public string Dev_QC_No { get; set; } 34  35         [Description("设备质控序号")] 36         public string Dev_QC_SequenceNo { get; set; } 37  38         [Description("设备质控名称")] 39         public string Dev_QC_Name { get; set; } 40  41         [Description("质控时间")] 42         public string QCTime { get; set; } 43  44         [Description("值类型")] 45         public string TextType { get; set; } 46  47         [Description("数值")] 48         public string ItemValue { get; set; } 49  50         [Description("创建时间")] 51         public string CreateTime { get; set; } 52  53         [Description("创建人")] 54         public string CreateUser { get; set; } 55  56         [Description("序号(通道号)")] 57         public string Serial { get; set; } 58  59         #endregion 60  61         ///  62         /// 设置属性值 63         ///  64         /// 名称 65         /// 值 66         public void SetAttributeValue(string name, string value) 67         { 68             switch (name) 69             { 70                 case "LogID"://数据日志编号 71                     this.LogID = value; 72                     break; 73                 case "DeviceID"://设备编号 74                     this.DeviceID = value; 75                     break; 76                 case "DeviceName"://设备名称 77                     this.DeviceName = value; 78                     break; 79                 case "QCItemDicID"://质控项目编号 80                     this.QCItemDicID = value; 81                     break; 82                 case "CNName"://质控项目中文名称 83                     this.CNName = value; 84                     break; 85                 case "ENName"://质控项目英文名称 86                     this.ENName = value; 87                     break; 88                 case "JPM"://质控项目名称简拼码 89                     this.JPM = value; 90                     break; 91                 case "NameAB"://质控项目名称简拼码 92                     this.NameAB = value; 93                     break; 94                 case "Unit"://质控项目单位 95                     this.Unit = value; 96                     break; 97                 case "Dev_QC_No"://设备质控编号 98                     this.Dev_QC_No = value; 99                     break;100                 case "Dev_QC_SequenceNo"://设备质控序号101                     this.Dev_QC_SequenceNo = value;102                     break;103                 case "Dev_QC_Name"://设备质控名称104                     this.Dev_QC_Name = value;105                     break;106                 case "QCTime"://质控时间107                     this.QCTime = value;108                     break;109                 case "TextType"://值类型110                     this.TextType = value;111                     break;112                 case "ItemValue"://数值113                     this.ItemValue = value;114                     break;115                 case "CreateTime"://创建时间116                     this.CreateTime = value;117                     break;118                 case "CreateUser"://创建人119                     this.CreateUser = value;120                     break;121                 case "Serial"://序号(通道号)122                     this.Serial = value;123                     break;124                 default:125                     break;126             }127         }128     }
View Code

 另外也可以把对象转换成DataTable或Dataset 根据具体使用的情况进行具体的转换

1 #region 获取对象和对象转换成DataTable  2   3         ///   4         /// 返回数据列  5         ///   6         ///   7         ///   8         /// 
9 public static DataColumn AddDataColumn(string columnName, string caption) 10 { 11 DataColumn dc = new DataColumn(); 12 13 dc.ColumnName = columnName; 14 dc.Caption = caption; 15 16 return dc; 17 } 18 19 /// 20 /// 获取表格的数据列 21 /// 22 /// 23 /// 24 ///
25 public static DataColumn GetColumn(string name, string caption) 26 { 27 DataColumn dc = new DataColumn(); 28 29 dc.ColumnName = name; 30 dc.Caption = caption; 31 32 return dc; 33 } 34 35 /// 36 /// 获取对象的属性名称、值和描述 37 /// 38 ///
对象的类型
39 /// 对象 40 ///
对象列表
41 public static List
GetProperties
(T t) 42 { 43 List
list = new List
(); 44 45 if (t == null) 46 { 47 return list; 48 } 49 System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); 50 51 if (properties.Length <= 0) 52 { 53 return list; 54 } 55 foreach (System.Reflection.PropertyInfo item in properties) 56 { 57 string name = item.Name; //名称 58 object value = item.GetValue(t, null); //值 59 string des = string.Empty; 60 61 try 62 { 63 des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值 64 } 65 catch { } 66 67 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) 68 { 69 Parameter parameter = new Parameter(); 70 71 parameter.Name = name; 72 parameter.Value = value == null ? string.Empty : value.ToString(); 73 parameter.Object = des; 74 75 list.Add(parameter); 76 } 77 else 78 { 79 GetProperties(value); 80 } 81 } 82 return list; 83 } 84 85 ///
86 /// 87 /// 88 ///
89 ///
90 ///
91 ///
92 public static List
GetProperties
(T t, string[] exceptArray) 93 { 94 List
list = new List
(); 95 96 if (t == null) 97 { 98 return list; 99 }100 PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);101 102 if (properties.Length <= 0)103 {104 return list;105 }106 foreach (PropertyInfo item in properties)107 {108 string name = item.Name; //名称109 object value = item.GetValue(t, null); //值110 string des = string.Empty;111 112 try113 {114 des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值115 }116 catch (Exception ex)117 {118 des = string.Empty;119 }120 121 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))122 {123 if (!((IList)exceptArray).Contains(name))124 {125 Parameter parameter = new Parameter();126 127 parameter.Name = name;128 parameter.Value = value == null ? "" : value.ToString();129 parameter.Object = des;130 131 list.Add(parameter);132 }133 }134 else135 {136 GetProperties(value);137 }138 }139 return list;140 }141 142 ///
143 /// 类型对象生成DataTable144 /// 145 ///
146 ///
147 ///
148 public static DataTable TToDataTable
(T obj, List
listT)149 {150 DataTable dt = new DataTable();151 152 int flag = 0;153 154 if (listT != null)155 {156 foreach (T t in listT)157 {158 List
listProperty = GetProperties
(t);159 160 if (flag <= 0)161 {162 foreach (Parameter parameter in listProperty)163 {164 flag++;165 166 dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));167 }168 }169 170 DataRow dr = dt.NewRow();171 172 foreach (Parameter parameter in listProperty)173 {174 dr[parameter.Name] = parameter.Value;175 }176 177 dt.Rows.Add(dr);178 }179 }180 else181 {182 List
listProperty = GetProperties
(obj);183 184 foreach (Parameter parameter in listProperty)185 {186 dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));187 }188 189 DataRow dr = dt.NewRow();190 191 foreach (Parameter parameter in listProperty)192 {193 dr[parameter.Name] = parameter.Value;194 }195 196 dt.Rows.Add(dr);197 }198 199 return dt;200 }201 202 ///
203 /// 204 /// 205 ///
206 ///
207 ///
208 public static DataTable TToDataTable
(T obj)209 {210 return TToDataTable
(obj, null);211 }212 213 ///
214 /// 类型对象生成DataTable215 /// 216 ///
217 ///
218 ///
219 public static DataTable TToDataTable
(List
listT)220 {221 return TToDataTable
(default(T), listT);222 }223 224 ///
225 /// 生成参数226 /// 227 ///
228 ///
229 ///
230 public static Parameter GetParameter(string name, string value)231 {232 Parameter parameter = new Parameter();233 234 parameter.Name = name;235 parameter.Value = value;236 237 return parameter;238 }
View Code

 要是客户端为bs架构,用一下代码进行发送

1 ///  2         ///  3         ///  4         /// 
5 /// 6 public void SendDataObject
(T t) 7 { 8 string json = Newtonsoft.Json.JsonConvert.SerializeObject(t); 9 10 SendDataByJson(json);11 }
View Code

具体的后端向前端发送的代码可以参考如下:

1 #region 公共方法 2         ///  3         /// 向客户端发送数据 4         ///  5         /// 字符编码 6         /// 输出流的MIME类型 7         /// 输出的内容 8         public void SendData(Encoding contentEncoding, string contentType, string content) 9         {10             Response.Clear();11             Response.ContentEncoding = contentEncoding;12             Response.ContentType = contentType;13             Response.Write(content);14             Response.Flush();15             Response.End();16         }17         /// 18         /// 向客户端发送数据19         /// 20         /// 输出的内容21         public void SendData(string content)22         {23             SendData(Encoding.UTF8, "application/json", content);24         }25 26         public void SendDataFile(string filePath, string fileName)27         {28             System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);29 30             byte[] b = new Byte[fs.Length];31             fs.Read(b, 0, b.Length);32             fs.Flush();33             fs.Close();34 35             Response.Clear();36             Response.ClearHeaders();37             Response.Clear();38             Response.ClearHeaders();39             Response.Buffer = false;40             Response.ContentType = "application/octet-stream";41             Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));42             Response.AppendHeader("Content-Length", b.Length.ToString());43             fs.Close();44             fs.Close();45             if (b.Length > 0)46             {47                 Response.OutputStream.Write(b, 0, b.Length);48             }49             Response.Flush();50             Response.End();51         }52         /// 53         /// 通过json的形式发送文本54         /// 55         /// 要发送的内容56         public void SendDataByJson(string content)57         {58             SendData(Encoding.UTF8, "application/json", content);59         }60         /// 61         /// 向客户端发送数据62         /// 63         /// 输出的内容64         public void SendData(string contentType, string content)65         {66             SendData(Encoding.UTF8, contentType, content);67         }68         /// 69         /// 通过文本的形式发送文件70         /// 71         /// 要发送的内容72         public void SendDataByText(string content)73         {74             SendData(Encoding.UTF8, "text/plain", content);75         }76         /// 77         /// 处理错误消息78         /// 79         /// 要处理的消息80         /// 
处理之后的消息
81 public string DealErrorMsg(string message)82 {83 return message.Replace((char)13, (char)0).Replace((char)10, (char)0).Replace("\"", "'").Replace("\0", "");84 }85 86 #endregion
View Code

 

转载于:https://www.cnblogs.com/yuzhou133/p/4917943.html

你可能感兴趣的文章
JavaStuNote 5
查看>>
经验总结22--抓取HTML数据,HtmlAgilityPack(续)
查看>>
HDU 5360 Hiking(优先队列)2015 Multi-University Training Contest 6
查看>>
Permutation Test 置换检验
查看>>
喵哈哈村的魔法考试 Round #19 (Div.2) 题解
查看>>
添加商品验证商品是否存在的两种实现方式
查看>>
《java虚拟机》汇总所有关键要点
查看>>
Win7 VNC远程连接Centos桌面
查看>>
使用cookie记录页面跳转次数,然后从最后一级页面跳转回首页面
查看>>
Eclipse和MyEclipse工程描述符.classpath和.project和.mymetadata详解(转)
查看>>
2016年互联网企业收入规模统计及分析
查看>>
软件复杂性的通俗理解
查看>>
批量更新代码整理(代码库)从数组中批量取数据的方法
查看>>
Contiki源码+原理+功能+编程+移植+驱动+网络(转)
查看>>
检测用户命令序列异常——使用LSTM分类算法【使用朴素贝叶斯,类似垃圾邮件分类的做法也可以,将命令序列看成是垃圾邮件】...
查看>>
Centos6.5安装步骤(U盘安装)
查看>>
cf1060D. Social Circles(贪心)
查看>>
JSON Web Token(JWT)原理和用法介绍
查看>>
Mybatis连接mysql数据库出现乱码
查看>>
IP Helper API 使用方法
查看>>