简单的sql server->bs或cs数据交互模式
主要记录工作当中遇到的一些问题和总结的一些经验
客户端请求-->web服务接口-->sql 语句执行(存储在数据库中)-->web服务(客户端通过调用web服务接口)-->返回DataTable或Dataset(sql server)--> 统一的DataTable或Dataset转换成对象-->提交给客户端(xml、json等等其他的)
1、首先通过sql语句返回结果,返回的结果一般都以Dataset的形式和DataTable的形式返回。
2、统一的DataTable或Dataset转换成对象
#region 写对象信息 /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName, DataRow dr, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); List<Parameter> listParameter = GetProperties<T>(item, exceptArray); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>().ToString() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); if (this.dsResult.Tables.Contains(tableName))
{
DataRow dr = this.dsResult.Tables[tableName].Rows[]; List<Parameter> listParameter = GetProperties<T>(item); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); if (this.dsResult.Tables.Contains(tableName))
{
DataRow dr = this.dsResult.Tables[tableName].Rows[]; List<Parameter> listParameter = GetProperties<T>(item, exceptArray); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public List<T> WriteTObjectInfoList<T>(string tableName, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} List<T> list = new List<T>(); if (this.dsResult.Tables.Contains(tableName))
{
foreach (DataRow dr in this.dsResult.Tables[tableName].Rows)
{
T item = WriteTObjectInfo<T>(tableName, dr, exceptArray); list.Add(item);
}
} return list;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>().ToString() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public List<T> WriteTObjectInfoList<T>(string tableName)
{
return WriteTObjectInfoList<T>(tableName, new string[] { });
} #endregion
以上代码统一用泛型实现
比较实用的获取属性的代码
/// <summary>
/// 获取对象的属性名称、值和描述
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="t">对象</param>
/// <returns>对象列表</returns>
public List<Parameter> GetProperties<T>(T t)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值 string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch { } if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="exceptArray"></param>
/// <returns></returns>
public List<Parameter> GetProperties<T>(T t, string[] exceptArray)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch (Exception ex)
{
des = string.Empty;
} if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (!((IList)exceptArray).Contains(name))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
}
else
{
GetProperties(value);
}
}
return list;
}
基础的Parameter类
public class Parameter
{
/// <summary>
/// 名称
/// </summary>
private string _name = string.Empty; /// <summary>
/// 获取或设置名称
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
} /// <summary>
/// 值
/// </summary>
private string _value = string.Empty; /// <summary>
/// 获取或设置值
/// </summary>
public string Value
{
get { return this._value; }
set { this._value = value; }
} private object _object = null; public object Object
{
get { return this._object; }
set { this._object = value; }
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="name">名称</param>
/// <param name="value">值</param>
public Parameter(string name, string value)
{
this.Name = name;
this.Value = value;
} public Parameter(string name, object obj)
{
this.Name = name;
this.Object = obj;
} /// <summary>
/// 构造函数
/// </summary>
public Parameter()
{ } /// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(@"名称(Name):{0},值(Value):{1},对象(Object):{2}", this.Name, this.Value, this.Object);
}
}
对象例子(这个对象例子的类,这个类其实和上面的DataTable和Dataset是对应的,通过以上的操作可以把DataTable或Dataset转换成具体的对象),因为这个类是比较统一的可以用代码生成工具可以直接生成
public class Log
{
#region 属性 [Description("数据日志编号")]
public string LogID { get; set; } [Description("设备编号")]
public string DeviceID { get; set; } [Description("设备名称")]
public string DeviceName { get; set; } [Description("质控项目编号")]
public string QCItemDicID { get; set; } [Description("质控项目中文名称")]
public string CNName { get; set; } [Description("质控项目英文名称")]
public string ENName { get; set; } [Description("质控项目名称简拼码")]
public string JPM { get; set; } [Description("质控项目名称简拼码")]
public string NameAB { get; set; } [Description("质控项目单位")]
public string Unit { get; set; } [Description("设备质控编号")]
public string Dev_QC_No { get; set; } [Description("设备质控序号")]
public string Dev_QC_SequenceNo { get; set; } [Description("设备质控名称")]
public string Dev_QC_Name { get; set; } [Description("质控时间")]
public string QCTime { get; set; } [Description("值类型")]
public string TextType { get; set; } [Description("数值")]
public string ItemValue { get; set; } [Description("创建时间")]
public string CreateTime { get; set; } [Description("创建人")]
public string CreateUser { get; set; } [Description("序号(通道号)")]
public string Serial { get; set; } #endregion /// <summary>
/// 设置属性值
/// </summary>
/// <param name="name">名称</param>
/// <param name="value">值</param>
public void SetAttributeValue(string name, string value)
{
switch (name)
{
case "LogID"://数据日志编号
this.LogID = value;
break;
case "DeviceID"://设备编号
this.DeviceID = value;
break;
case "DeviceName"://设备名称
this.DeviceName = value;
break;
case "QCItemDicID"://质控项目编号
this.QCItemDicID = value;
break;
case "CNName"://质控项目中文名称
this.CNName = value;
break;
case "ENName"://质控项目英文名称
this.ENName = value;
break;
case "JPM"://质控项目名称简拼码
this.JPM = value;
break;
case "NameAB"://质控项目名称简拼码
this.NameAB = value;
break;
case "Unit"://质控项目单位
this.Unit = value;
break;
case "Dev_QC_No"://设备质控编号
this.Dev_QC_No = value;
break;
case "Dev_QC_SequenceNo"://设备质控序号
this.Dev_QC_SequenceNo = value;
break;
case "Dev_QC_Name"://设备质控名称
this.Dev_QC_Name = value;
break;
case "QCTime"://质控时间
this.QCTime = value;
break;
case "TextType"://值类型
this.TextType = value;
break;
case "ItemValue"://数值
this.ItemValue = value;
break;
case "CreateTime"://创建时间
this.CreateTime = value;
break;
case "CreateUser"://创建人
this.CreateUser = value;
break;
case "Serial"://序号(通道号)
this.Serial = value;
break;
default:
break;
}
}
}
另外也可以把对象转换成DataTable或Dataset 根据具体使用的情况进行具体的转换
#region 获取对象和对象转换成DataTable /// <summary>
/// 返回数据列
/// </summary>
/// <param name="columnName"></param>
/// <param name="caption"></param>
/// <returns></returns>
public static DataColumn AddDataColumn(string columnName, string caption)
{
DataColumn dc = new DataColumn(); dc.ColumnName = columnName;
dc.Caption = caption; return dc;
} /// <summary>
/// 获取表格的数据列
/// </summary>
/// <param name="name"></param>
/// <param name="caption"></param>
/// <returns></returns>
public static DataColumn GetColumn(string name, string caption)
{
DataColumn dc = new DataColumn(); dc.ColumnName = name;
dc.Caption = caption; return dc;
} /// <summary>
/// 获取对象的属性名称、值和描述
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="t">对象</param>
/// <returns>对象列表</returns>
public static List<Parameter> GetProperties<T>(T t)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch { } if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? string.Empty : value.ToString();
parameter.Object = des; list.Add(parameter);
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="exceptArray"></param>
/// <returns></returns>
public static List<Parameter> GetProperties<T>(T t, string[] exceptArray)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch (Exception ex)
{
des = string.Empty;
} if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (!((IList)exceptArray).Contains(name))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
/// 类型对象生成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(T obj, List<T> listT)
{
DataTable dt = new DataTable(); int flag = ; if (listT != null)
{
foreach (T t in listT)
{
List<Parameter> listProperty = GetProperties<T>(t); if (flag <= )
{
foreach (Parameter parameter in listProperty)
{
flag++; dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));
}
} DataRow dr = dt.NewRow(); foreach (Parameter parameter in listProperty)
{
dr[parameter.Name] = parameter.Value;
} dt.Rows.Add(dr);
}
}
else
{
List<Parameter> listProperty = GetProperties<T>(obj); foreach (Parameter parameter in listProperty)
{
dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));
} DataRow dr = dt.NewRow(); foreach (Parameter parameter in listProperty)
{
dr[parameter.Name] = parameter.Value;
} dt.Rows.Add(dr);
} return dt;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(T obj)
{
return TToDataTable<T>(obj, null);
} /// <summary>
/// 类型对象生成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listT"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(List<T> listT)
{
return TToDataTable<T>(default(T), listT);
} /// <summary>
/// 生成参数
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Parameter GetParameter(string name, string value)
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value; return parameter;
}
要是客户端为bs架构,用一下代码进行发送
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void SendDataObject<T>(T t)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(t); SendDataByJson(json);
}
具体的后端向前端发送的代码可以参考如下:
#region 公共方法
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="contentEncoding">字符编码</param>
/// <param name="contentType">输出流的MIME类型</param>
/// <param name="content">输出的内容</param>
public void SendData(Encoding contentEncoding, string contentType, string content)
{
Response.Clear();
Response.ContentEncoding = contentEncoding;
Response.ContentType = contentType;
Response.Write(content);
Response.Flush();
Response.End();
}
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="content">输出的内容</param>
public void SendData(string content)
{
SendData(Encoding.UTF8, "application/json", content);
} public void SendDataFile(string filePath, string fileName)
{
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] b = new Byte[fs.Length];
fs.Read(b, , b.Length);
fs.Flush();
fs.Close(); Response.Clear();
Response.ClearHeaders();
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", b.Length.ToString());
fs.Close();
fs.Close();
if (b.Length > )
{
Response.OutputStream.Write(b, , b.Length);
}
Response.Flush();
Response.End();
}
/// <summary>
/// 通过json的形式发送文本
/// </summary>
/// <param name="content">要发送的内容</param>
public void SendDataByJson(string content)
{
SendData(Encoding.UTF8, "application/json", content);
}
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="content">输出的内容</param>
public void SendData(string contentType, string content)
{
SendData(Encoding.UTF8, contentType, content);
}
/// <summary>
/// 通过文本的形式发送文件
/// </summary>
/// <param name="content">要发送的内容</param>
public void SendDataByText(string content)
{
SendData(Encoding.UTF8, "text/plain", content);
}
/// <summary>
/// 处理错误消息
/// </summary>
/// <param name="message">要处理的消息</param>
/// <returns>处理之后的消息</returns>
public string DealErrorMsg(string message)
{
return message.Replace((char), (char)).Replace((char), (char)).Replace("\"", "'").Replace("\0", "");
} #endregion
简单的sql server->bs或cs数据交互模式的更多相关文章
- 最简单删除SQL Server中所有数据的方法
最简单删除SQL Server中所有数据的方法 编写人:CC阿爸 2014-3-14 其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间 ...
- 恢复SQL Server被误删除的数据(再扩展)
恢复SQL Server被误删除的数据(再扩展) 大家对本人之前的文章<恢复SQL Server被误删除的数据> 反应非常热烈,但是文章里的存储过程不能实现对备份出来的日志备份里所删数据的 ...
- 恢复SQL Server被误删除的数据
恢复SQL Server被误删除的数据 <恢复SQL Server被误删除的数据(再扩展)> 地址:http://www.cnblogs.com/lyhabc/p/4620764.html ...
- 转:Sql Server中清空所有数据表中的记录
如果要删除数据表中所有数据只要遍历一下数据库再删除就可以了,清除所有数据我们可以使用搜索出所有表名,构造为一条SQL语句进行清除了,这里我一一给各位同学介绍. 使用sql删除数据库中所有表是不难的 ...
- Sql Server中清空所有数据表中的记录
Sql Server中清空所有数据表中的记录 清空所有数据表中的记录: 代码如下:exec sp_msforeachtable @Command1 ='truncate table ?'删除所有数据 ...
- SQL SERVER 和ACCESS的数据导入导出
//批量导入Access string filepath = Server.MapPath("student.mdb"); stri ...
- .SQL Server中 image类型数据的比较
原文:.SQL Server中 image类型数据的比较 在SQL Server中如果你对text.ntext或者image数据类型的数据进行比较.将会提示:不能比较或排序 text.ntext 和 ...
- [转]实战 SQL Server 2008 数据库误删除数据的恢复
实战 SQL Server 2008 数据库误删除数据的恢复 关键字:SQL Server 2008, recover deleted records 今天有个朋友很着急地打电话给我,他用delete ...
- SQL Server 2008 数据库误删除数据的恢复
原文:SQL Server 2008 数据库误删除数据的恢复 原文:http://www.cnblogs.com/dudu/archive/2011/10/15/sql_server_recover_ ...
随机推荐
- Unity导入fbx格式的模型
1. 在Model文件夹右击,选择 import new Asset,然后选择要导入的模型 2. 将纹理图片导入Pictures中 3. 在Materials中创建一个Material,然后点击属性中 ...
- 异常:Project configuration is not up-to-date with pom.xml 解决方案
错误描述,在导入Maven项目后出现下面错误: Description Resource Path Location Type Project configuration is not up-to-d ...
- css布局 - 工作中常见的两栏布局案例及分析
突然想到要整理这么一篇平时工作中相当常见但是我们又很忽视的布局的多种处理方法.临时就在我经常浏览的网站上抓的相对应的截图.(以后看到其他类型的我再补充) 既然截了图,咱们就直接看人家使用的布局方式,毕 ...
- react proxy 报错
react项目中,package.json中proxy的配置如下 "proxy": { "/api/rjwl": { "target": & ...
- MySql的主从复制以及读写分离详解
MySQL主从复制(Master-Slave)与读写分离(MySQL-Proxy)实践 Mysql作为目前世界上使用最广泛的免费数据库,相信所有从事系统运维的工程师都一定接触过.但在实际的生产环境中, ...
- ubuntu14.04 LTS 更新国内网易163源
2015/10/7 更改ubuntu的默认源是linux学习中必须掌握的基础技能.在此记录,以作参考. 在ubuntu14.04 LTS默认使用的是国外源,由于网络的原因,使用apt-get安装包时异 ...
- SpringMVC+MyBatis+Druid使用MySQL8.0.11版本
1.使用MySQL8.0.11版本,要使用5.1.45或其他高版本驱动jar包,我本地使用的是最新的8.0.11 2.更换了MySQL驱动后,报Cannot find class [com.aliba ...
- 终于解决 xUnit.net 测试中无法输出到控制台的问题
2018-8-2 更新:今天发现在 git bash 中用 dotnet test 运行 xunit 测试可以正常输出到控制台,只是在 PowerShell 与 Windows 命令行中有这个问题. ...
- Windows10 家庭版 关闭Windows defender
管理员权限打开cmd,输入下面命令: reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender&quo ...
- 【UML】-NO.44.EBook.5.UML.1.004-【UML 大战需求分析】- 顺序图(Sequence Diagram)
1.0.0 Summary Tittle:[UML]-NO.44.EBook.1.UML.1.004-[UML 大战需求分析]- 顺序图(Sequence Diagram) Style:DesignP ...