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的更多相关文章

  1. SQLServer数据库通用访问类

    private static string connString=ConfigurationManager.ConnStrings["connString"].ToString() ...

  2. 针对SQLServer数据库的通用访问类

    Web.config中代码 <configuration> <connectionStrings> <add name="connString" co ...

  3. 【转载】微软官方提供的Sqlserver数据库操作帮助类SQLHelper类

    在.NET平台中,C#语言一般使用ADO.NET组件来操作Sqlserver数据库,通过ADO.NET组件可以实现连接数据库.查询数据集.执行SQL语句以及关闭数据库连接等操作,为此网上有很多开发者自 ...

  4. C# SQL数据库的访问类

    /// <summary> /// SQL数据库的访问类 /// </summary> public class SQLHelper { /// <summary> ...

  5. SQLserver数据库操作帮助类SqlHelper

    1 SqlHelper源码 using System; using System.Data; using System.Xml; using System.Data.SqlClient; using ...

  6. Ado.net 通用访问类

    public class DbHelperSQL { private static string connString = ConfigurationManager.ConnectionStrings ...

  7. C# 通用数据访问类(SqlHelper)

    [转]C# 通用数据访问类(SqlHelper) 注:本文转自http://www.tzwhx.com/newOperate/html/3/31/312/13080.htmlVisual C# 动态操 ...

  8. DataAccess通用数据库访问类,简单易用,功能强悍

    以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...

  9. 一个通用数据库访问类(C#,SqlClient)

    本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...

随机推荐

  1. bzoj 3028 食物——生成函数

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3028 把式子写出来,化一化,变成 x / ((1-x)^4) ,变成几个 sigma 相乘的 ...

  2. [Angularjs-学习笔记]工具篇

    因为一开始学习前端知识一直都是在慕课网,所以这次准备学习下angularjs等了好久,终于慕课网出了angularjs的内容,于是准备开始跟着老师的步骤进行学习. 大漠老师关于开发工具的内容讲得比较快 ...

  3. DripRoad(点滴之路)

    关于DripRoad DripRoad 意为点滴之路,程序员之路在于点滴积累!是的,这些积累包括技术能力,沟通能力,业务能力等等.   我 我是唐志伟,2009年一个人来上海,就读于上海医疗器械高等专 ...

  4. leetcode Single Number II - 位运算处理数组中的数

    题目描述: 给定一个包含n个整数的数组,除了一个数出现一次外所有的整数均出现三次,找出这个只出现一次的整数. 题目来源: http://oj.leetcode.com/problems/single- ...

  5. 简单的触发黑名单阻断演示 control+c

    #include "stdafx.h"#include <signal.h>#include <windows.h> #include <iostre ...

  6. Solaris10 如何设置空闲ssh连接超时断开

    在ssh的配置文件中有2个参数可以控制空闲连接超时断开.这2个参数是ClientAliveCountMax和ClientAliveInterval. Solaris10上设置空闲ssh连接超时断开的方 ...

  7. onclick事件没有反应的五种可能情况

    转自:https://blog.csdn.net/qujing_1120/article/details/76853039 onclick=”alert()” 事件没有反应的几种情况.第一:<i ...

  8. Delphi 转圈 原型进度条 AniIndicator 及线程配合使用

    Delphi FMX 转圈 原型进度条 progress AniIndicator TAniIndicator TFloatAnimation VCL下也有转圈菊花进度条 TActivityIndic ...

  9. 使用NDK编译 libyuv <转>

    官方源码:http://code.google.com/p/libyuv/简介: libyuv is an open source project that includes YUV scaling ...

  10. Aborted connection+druid

    试一试setTimeBetweenEvictionRunsMillis +setMaxEvictableIdleTimeMillis小于 mysql的wait_timeout