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 ...
随机推荐
- [Project Euler] 来做欧拉项目练习题吧: 题目013
问题描述: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 371072 ...
- Operating System-进程间互斥的方案-保证同一时间只有一个进程进入临界区(3)- TSL指令
本文接上一篇文章继续介绍如何实现同一时间只允许一个进程进入临界区的机制.本文主要介绍TSL指令. 方案汇总 屏蔽中断 锁变量 严格轮换法 TSL指令 Peterson解法 一.What is TSL ...
- h5的video标签支持的视频格式
关于<video>标签所支持的视频格式和编码: MP4 = MPEG 4文件使用 H264 视频编解码器和AAC音频编解码器 WebM = WebM 文件使用 VP8 视频编解码器和 Vo ...
- CentOS 7.2 PowerShell下安装Azure Module
目前Linux版本的PowerShell还是Alpha版本,所以很多功能不能使用. 比如通过Powershell命令:install-module AzureRM在线安装Azure的Module.但我 ...
- [转载]create_proc_read_entry中函数的说明
原型: struct proc_dir_entry *create_proc_read_entry (const char *name, mode_t mode, struct proc_dir_en ...
- __thiscalll C++底层识别成员函数
问题描述: class myClass { public: void SetNumber(int nNumber) { m_nInt = nNumber; } private: int m_nInt; ...
- WebApi学习系列
最近有一些时间,打算学习和整理一下Web API的一些学习资料的翻译工作.以下是对Web API 的大概目录的整理.欢迎更多的朋友一起加入到学习Web API 的队伍中来,如果你想贡献自己的,请联 ...
- Python函数(五)-高阶函数
函数接收的参数可以是数字,字符串,列表,元组,字典,集合,也可以是另一个函数,那么这个接收一个函数作为参数的函数就称为高阶函数 # -*- coding:utf-8 -*- __author__ = ...
- Eclipse中classpath和deploy assembly的文件位置
classpath的配置信息存储在工程根目录下的.classpath文件 deploy assembly配置信息存储在工程目录下的.settings\org.eclipse.wst.common.co ...
- dtgrid 手动条件删除表格中的某一行
dtgrid 手动条件删除表格中的某一行 var grid = $.fn.DtGrid.init(dtGridOption); $(function () { grid.load(); }); fun ...