C#:数据库通用访问类 SqlHelper
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Reflection; using System.Configuration;
namespace CarolLib
{
public static class SqlHelper
{
#region Execute private static int commandTimeOut = string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]) ? : int.Parse(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]); public static SqlDataReader ExecuteReader(SqlConnection conn, String name, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(name, conn))
{
command.CommandTimeout = commandTimeOut;
command.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
} public static SqlDataReader ExecuteReader(SqlConnection conn, String name, CommandType type, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(name, conn))
{
command.CommandTimeout = commandTimeOut;
command.CommandType = type;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
} public static object ExecuteScalar(SqlConnection conn, String name, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(name, conn))
{ command.CommandTimeout = commandTimeOut;
command.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
object returnValue = command.ExecuteScalar();
conn.Close();
return returnValue;
}
} public static object ExecuteScalar(SqlConnection conn, string sql, string type, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(sql, conn))
{ command.CommandTimeout = commandTimeOut;
command.CommandType = CommandType.Text;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
object returnValue = command.ExecuteScalar();
conn.Close();
return returnValue;
}
} public static long ExecuteNonQuery(SqlConnection conn, String name, CommandType type, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(name, conn))
{ command.CommandType = type;
command.CommandTimeout = commandTimeOut;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
long returnValue = command.ExecuteNonQuery();
conn.Close();
return returnValue;
}
} public static long ExecuteNonQuery(SqlConnection conn, String name, params SqlParameter[] parameters)
{
try
{
using (SqlCommand command = new SqlCommand(name, conn))
{ command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = commandTimeOut;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
long returnValue = command.ExecuteNonQuery();
conn.Close();
return returnValue;
}
}
catch (Exception ex)
{
ex.Data["name"] = name;
int i = ;
foreach (var para in parameters)
{
ex.Data["para" + i] = para.Value;
i++;
} throw;
}
} public static T ExecuteWithReturn<T>(SqlConnection conn, String name, params SqlParameter[] parameters)
{
using (SqlCommand command = new SqlCommand(name, conn))
{
command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = commandTimeOut;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, , ParameterDirection.ReturnValue,
false, , , string.Empty, DataRowVersion.Default, null));
conn.Open();
command.ExecuteNonQuery();
T returnValue = (T)command.Parameters["ReturnValue"].Value;
conn.Close();
return returnValue;
}
} public static DataSet ExecuteDataSet(SqlConnection conn, String name, params SqlParameter[] parameters)
{
using (SqlDataAdapter da = new SqlDataAdapter(name, conn))
{
using (SqlCommand command = new SqlCommand(name, conn))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
DataSet ds = new DataSet(); da.SelectCommand = command;
da.Fill(ds); return ds;
}
}
} //返回SqlCommand
public static SqlCommand CreateCmd(string proName, SqlParameter[] prams, SqlConnection Conn)
{
SqlConnection SqlConn = Conn;
if (SqlConn.State.Equals(ConnectionState.Closed))
{
SqlConn.Open(); //关闭
}
SqlCommand Cmd = new SqlCommand();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Connection = SqlConn;
Cmd.CommandText = proName;
if (prams != null)
{
foreach (SqlParameter Parameter in prams)
{
if (Parameter != null)
{
Cmd.Parameters.Add(Parameter);
}
}
}
return Cmd;
}
//重载返回SqlCommand
public static SqlCommand CreateCmd(string sqlStr, SqlParameter[] prams, SqlConnection Conn, CommandType Ctype)
{
SqlConnection SqlConn = Conn;
if (SqlConn.State.Equals(ConnectionState.Closed))
{
SqlConn.Open();
}
SqlCommand Cmd = new SqlCommand();
Cmd.CommandType = Ctype;
Cmd.Connection = SqlConn;
Cmd.CommandText = sqlStr;
if (prams != null)
{
foreach (SqlParameter parameter in prams)
{
if (parameter != null)
{
Cmd.Parameters.Add(parameter);
}
}
}
return Cmd;
} //返回DataTable
public static DataTable RunProGetTable(string proName, SqlParameter[] prams, SqlConnection Conn)
{
try
{
SqlCommand Cmd = CreateCmd(proName, prams, Conn);
SqlDataAdapter Da = new SqlDataAdapter();
DataSet Ds = new DataSet();
Da.SelectCommand = Cmd;
Da.Fill(Ds);
DataTable Dt = Ds.Tables[];
return Dt; }
catch (Exception ex)
{
throw ex;
}
finally
{
Conn.Close();
}
} public static DataTable RunProGetTable(string sqlStr, SqlParameter[] prams, SqlConnection Conn, CommandType Ctype)
{
try
{
SqlCommand Cmd = CreateCmd(sqlStr, prams, Conn, Ctype);
SqlDataAdapter Da = new SqlDataAdapter();
DataSet Ds = new DataSet();
Da.SelectCommand = Cmd;
Da.Fill(Ds);
DataTable Dt = Ds.Tables[];
return Dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
Conn.Close(); } } #endregion #region Create Parameter public static SqlParameter CreateNTextInParameter(String name, String s)
{
return CreateInParameter(name, SqlDbType.NText,
s != null ? s.Length : , s);
} public static SqlParameter CreateImageInParameter(String name, Byte[] bytes)
{
return CreateInParameter(name, SqlDbType.Image,
bytes != null ? bytes.Length : , bytes);
} public static SqlParameter CreateInParameter(String name, SqlDbType datatype, int size, Object value)
{
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = name;
parameter.Direction = ParameterDirection.Input;
parameter.SqlDbType = datatype;
parameter.Size = size;
parameter.Value = value;
return parameter;
} public static SqlParameter CreateOutParameter(String name, SqlDbType datatype, int size)
{
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = name;
parameter.Direction = ParameterDirection.Output;
parameter.SqlDbType = datatype;
parameter.Size = size;
return parameter;
} #endregion #region Ids public static object IDFromString(String id)
{
return id != null && id.Length > ? (object)Int64.Parse(id) : DBNull.Value;
} public static string CleanSearchString(string searchString)
{
if (string.IsNullOrEmpty(searchString))
return null; // Do wild card replacements
searchString = searchString.Replace("*", "%"); // Strip any markup characters
//searchString = Transforms.StripHtmlXmlTags(searchString); // Remove known bad SQL characters
searchString = Regex.Replace(searchString, "--|;|'|\"", " ", RegexOptions.Compiled | RegexOptions.Multiline); // Finally remove any extra spaces from the string
searchString = Regex.Replace(searchString, " {1,}", " ", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline); return searchString;
} public static List<int> PopulateReadersToIds(IDataReader dr, string key)
{
return PopulateReadersToIds<int>(dr, key);
} public static List<T> PopulateReadersToIds<T>(IDataReader dr, string key)
{
List<T> ids = new List<T>();
//Dictionary<T, bool> existsIds = new Dictionary<T, bool>();
while (dr.Read())
{
T id = (T)dr[key];
//if (!existsIds.ContainsKey(id))
//{
//existsIds.Add(id, true);
ids.Add(id);
//}
}
return ids;
} /// <summary>
/// convert datareader to dictionary
/// </summary>
/// <param name="dr"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Dictionary<string, DateTime> PopulateReadersToDic(IDataReader dr, string key, string value)
{
return PopulateReadersToDic<string, DateTime>(dr, key, value);
} public static Dictionary<T1, T2> PopulateReadersToDic<T1, T2>(IDataReader dr, string key, string value)
{
Dictionary<T1, T2> result = new Dictionary<T1, T2>(); while (dr.Read())
{
T1 name = (T1)dr[key];
T2 date = (T2)dr[value]; result.Add(name, date); }
return result; } public static object ConvertIdsToXML<T>(string itemName, T[] ids)
{
string rootName = itemName + "s";
string idName = "i";
return ConvertIdsToXML<T>(rootName, itemName, idName, ids);
} public static object ConvertModelListToXML<T>(string itemName, IEnumerable<T> modelList)
{
if (modelList == null)
{
return DBNull.Value;
} StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.WriteStartElement(itemName + "s"); var type = typeof(T);
if (type.IsValueType)
{//添加对值类型的支持
foreach (T model in modelList)
{
writer.WriteStartElement(itemName);
writer.WriteAttributeString(type.Name, type.IsEnum ? Convert.ToInt32(model).ToString() : model.ToString());
writer.WriteEndElement();
}
}
else
{
foreach (T model in modelList)
{
writer.WriteStartElement(itemName);
foreach (PropertyInfo p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
try
{
if (p.PropertyType.IsGenericType)
{
var ut = Nullable.GetUnderlyingType(p.PropertyType);
if (ut != null && ut.IsEnum)
{
var v = p.GetValue(model, null);
if (v == null)
{
writer.WriteAttributeString(p.Name, string.Empty);
}
else
{
writer.WriteAttributeString(p.Name, Convert.ToString((int)v));
}
//writer.WriteAttributeString(p.Name, Convert.ToString((int?)p.GetValue(model, null)));
}
else
{
writer.WriteAttributeString(p.Name, Convert.ToString(p.GetValue(model, null)));
}
}
else if (p.PropertyType.IsEnum)
writer.WriteAttributeString(p.Name, Convert.ToString((int)p.GetValue(model, null)));
else
writer.WriteAttributeString(p.Name, Convert.ToString(p.GetValue(model, null)));
}
catch (Exception e)
{
throw e;
}
}
writer.WriteEndElement();
}
}
writer.WriteEndElement();
writer.Close();
return sw.ToString();
} public static object ConvertIdsToXML<T>(string rootName, string itemName, string idName, T[] ids)
{
if (ids == null)
return DBNull.Value; StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.WriteStartElement(rootName);
foreach (T id in ids)
{
writer.WriteStartElement(itemName);
writer.WriteAttributeString(idName, typeof(T).IsEnum ? Convert.ToInt32(id).ToString() : id.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Close();
return sw.ToString();
} #endregion #region SQL TypeSafe public static object GetSafeSqlDateTime(DateTime? date)
{
if (date == null)
return DBNull.Value;
return GetSafeSqlDateTime(date.Value);
} public static DateTime GetSafeSqlDateTime(DateTime date)
{
if (date < SqlDateTime.MinValue)
{
return (DateTime)SqlDateTime.MinValue;
}
if (date > SqlDateTime.MaxValue)
{
return (DateTime)SqlDateTime.MaxValue;
}
return date;
} public static string GetSafeSqlDateTimeFormat(DateTime date)
{
return date.ToString(CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern);
} public static int GetSafeSqlInt(int i)
{
if (i <= ((int)SqlInt32.MinValue))
{
return (((int)SqlInt32.MinValue) + );
}
if (i >= ((int)SqlInt32.MaxValue))
{
return (((int)SqlInt32.MaxValue) - );
}
return i;
} public static object StringOrNull(string text)
{
if (string.IsNullOrEmpty(text))
{
return DBNull.Value;
}
return text;
} #endregion
}
}
C#:数据库通用访问类 SqlHelper的更多相关文章
- SQLServer数据库通用访问类
private static string connString=ConfigurationManager.ConnStrings["connString"].ToString() ...
- 针对SQLServer数据库的通用访问类
Web.config中代码 <configuration> <connectionStrings> <add name="connString" co ...
- 【转载】微软官方提供的Sqlserver数据库操作帮助类SQLHelper类
在.NET平台中,C#语言一般使用ADO.NET组件来操作Sqlserver数据库,通过ADO.NET组件可以实现连接数据库.查询数据集.执行SQL语句以及关闭数据库连接等操作,为此网上有很多开发者自 ...
- C# SQL数据库的访问类
/// <summary> /// SQL数据库的访问类 /// </summary> public class SQLHelper { /// <summary> ...
- SQLserver数据库操作帮助类SqlHelper
1 SqlHelper源码 using System; using System.Data; using System.Xml; using System.Data.SqlClient; using ...
- Ado.net 通用访问类
public class DbHelperSQL { private static string connString = ConfigurationManager.ConnectionStrings ...
- C# 通用数据访问类(SqlHelper)
[转]C# 通用数据访问类(SqlHelper) 注:本文转自http://www.tzwhx.com/newOperate/html/3/31/312/13080.htmlVisual C# 动态操 ...
- DataAccess通用数据库访问类,简单易用,功能强悍
以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...
- 一个通用数据库访问类(C#,SqlClient)
本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...
随机推荐
- c++运行时决定数组大小 variable-length array
本文由Suzzz原创,发布于 http://www.cnblogs.com/Suzzz/p/4117431.html,转载请保留此声明 variable-length array是C99添加的一个特性 ...
- 【转载,实测好用】gitlab结合sourcetree使用
转载 的出处http://blog.csdn.net/u012764358/article/details/62886427 Gitlab和Sourcetree结合使用实现代码管理 这是本人第一次发表 ...
- Springboot正常启动,但是访问404报错
原因: 查看是否配置文件中有以下配置: server.context-path=/hellopath 我这里是以/hellopath为例,如果有该配置的话,只能通过该路径访问到. 其他原因
- MySQL自带的性能压力测试工具mysqlslap详解
使用语法如下:# mysqlslap [options] 常用参数 [options] 详细说明: --auto-generate-sql, -a 自动生成测试表和数据,表示用mysqlslap工具自 ...
- H264系列(9):H264中的时间戳(DTS和PTS)
(1)Ffmpeg中的DTS 和 PTS H264里有两种时间戳:DTS(Decoding Time Stamp)和PTS(Presentation Time Stamp). 顾名思义,前者是解码的时 ...
- boot asio 非阻塞同步编程---非阻塞的accept和receive。
boot asio 非阻塞同步编程---非阻塞的accept和receive. 客户端编程: #include<boost/timer.hpp> #include <iostream ...
- 【转】 Pro Android学习笔记(八十):服务(5):访问远程服务
目录(?)[-] Client的AIDL文件 Client的代码 建立连接 请求服务 断开连接 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://bl ...
- L2-004. 这是二叉搜索树吗?(前序转后序递归)
L2-004. 这是二叉搜索树吗? 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 一棵二叉搜索树可被递归地定义为具有下列性质的 ...
- HTML5的离线应用
参考:有趣的HTML5:离线存储——segmentfault HTML5的离线存储 简介 HTML5提供了很多新的功能以及相应的接口,离线存储就是其中的一个.通过浏览器访问Web App需要联网发送请 ...
- Celery-4.1 用户指南: Workers Guide (Workers 指南)
启动工作单元 你可以通过执行以下命令在前台启动工作单元: $ celery -A proj worker -l info 查看启动工作单元的可用命令行选项,可以执行: $ celery worker ...