防止连接泄漏的两种SQLHelper.cs文件写法
下面的两个类,对SQL的连接对象进行了严格的控制,可以有效的防止连接的 泄漏
第一种:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;
using System.Reflection;
namespace BaseClass
{
public class SqlHelper2
{
protected static string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
#region 执行简单SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, conn))
{
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSQL, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
connection.Close();
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader(此方法不能用,没有关闭连接)(因为SqlConnection对象是在方法内定义的,外部无法关闭)
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 从上面的ExecuteReader不能用,改成下面的方法,但打开连接是从此方法中进行,要从此方法外(调用处)关闭连接(我自己写的方法)
/// </summary>
/// <param name="strSQL"></param>
/// <param name="conn"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string strSQL, SqlConnection conn)
{
// SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, conn);
try
{
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
if (connection.State ==ConnectionState.Open)
connection.Close();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
// connection.Close();
}
return ds;
}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
connection.Open();
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
connection.Close();
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
finally
{
conn.Close();
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
connection.Open();
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
connection.Close();
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader(此方法不能用,没有关闭连接)
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
connection.Open();//连接没有关闭
SqlDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
//if (conn.State != ConnectionState.Open)
// conn.Open();//??
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
#region 存储过程操作
/// <summary>
/// 执行存储过程(此方法不能用,没有关闭连接)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader returnReader;
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.CommandType = CommandType.StoredProcedure;
returnReader = command.ExecuteReader();
return returnReader;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
return command;
}
/// <summary>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int result;
connection.Open();
SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
connection.Close();
return result;
}
}
/// <summary>
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand 对象实例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
#endregion
#region 由Object取值
/// <summary>
/// 取得Int值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>int值</returns>
public static int GetInt(object obj)
{
if (obj.ToString() != "")
return int.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得byte值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>byte值</returns>
public static byte Getbyte(object obj)
{
if (obj.ToString() != "")
return byte.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 获得Long值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>long值</returns>
public static long GetLong(object obj)
{
if (obj.ToString() != "")
return long.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得Decimal值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>decimal值</returns>
public static decimal GetDecimal(object obj)
{
if (obj.ToString() != "")
return decimal.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得Guid值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>Guid值</returns>
public static Guid GetGuid(object obj)
{
if (obj.ToString() != "")
return new Guid(obj.ToString());
else
return Guid.Empty;
}
/// <summary>
/// 取得DateTime值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>DateTime值</returns>
public static DateTime GetDateTime(object obj)
{
if (obj.ToString() != "")
return DateTime.Parse(obj.ToString());
else
return DateTime.MinValue;
}
/// <summary>
/// 取得bool值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>bool值</returns>
public static bool GetBool(object obj)
{
if (obj.ToString() == "1" || obj.ToString().ToLower() == "true")
return true;
else
return false;
}
/// <summary>
/// 取得byte[]值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>byte[]值</returns>
public static Byte[] GetByte(object obj)
{
if (obj.ToString() != "")
{
return (Byte[])obj;
}
else
return null;
}
/// <summary>
/// 取得string值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>string值</returns>
public static string GetString(object obj)
{
return obj.ToString();
}
#endregion
#region 序列化与反序列化
/// <summary>
/// 序列化对象
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <returns>返回二进制</returns>
public static byte[] SerializeModel(Object obj)
{
if (obj != null)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] b;
binaryFormatter.Serialize(ms, obj);
ms.Position = 0;
b = new Byte[ms.Length];
ms.Read(b, 0, b.Length);
ms.Close();
return b;
}
else
return new byte[0];
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <param name="b">要反序列化的二进制</param>
/// <param name="SampleModel">Model的实体示例,New一个出来即可</param>
/// <returns>返回对象</returns>
public static object DeserializeModel(byte[] b, object SampleModel)
{
if (b == null || b.Length == 0)
return SampleModel;
else
{
object result = new object();
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
try
{
ms.Write(b, 0, b.Length);
ms.Position = 0;
result = binaryFormatter.Deserialize(ms);
ms.Close();
}
catch { }
return result;
}
}
#endregion
#region Model与XML互相转换
/// <summary>
/// Model转化为XML的方法
/// </summary>
/// <param name="model">要转化的Model</param>
/// <returns></returns>
public static string ModelToXML(object model)
{
XmlDocument xmldoc = new XmlDocument();
XmlElement ModelNode = xmldoc.CreateElement("Model");
xmldoc.AppendChild(ModelNode);
if (model != null)
{
foreach (PropertyInfo property in model.GetType().GetProperties())
{
XmlElement attribute = xmldoc.CreateElement(property.Name);
if (property.GetValue(model, null) != null)
attribute.InnerText = property.GetValue(model, null).ToString();
else
attribute.InnerText = "[Null]";
ModelNode.AppendChild(attribute);
}
}
return xmldoc.OuterXml;
}
/// <summary>
/// XML转化为Model的方法
/// </summary>
/// <param name="xml">要转化的XML</param>
/// <param name="SampleModel">Model的实体示例,New一个出来即可</param>
/// <returns></returns>
public static object XMLToModel(string xml, object SampleModel)
{
if (string.IsNullOrEmpty(xml))
return SampleModel;
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
XmlNodeList attributes = xmldoc.SelectSingleNode("Model").ChildNodes;
foreach (XmlNode node in attributes)
{
foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
{
if (node.Name == property.Name)
{
if (node.InnerText != "[Null]")
{
if (property.PropertyType == typeof(System.Guid))
property.SetValue(SampleModel, new Guid(node.InnerText), null);
else
property.SetValue(SampleModel, Convert.ChangeType(node.InnerText, property.PropertyType), null);
}
else
property.SetValue(SampleModel, null, null);
}
}
}
return SampleModel;
}
}
#endregion
}
}
第二种:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;
using System.Reflection;
namespace BaseClass
{
public class SqlHelper
{
protected static string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
private static SqlConnection conn = new SqlConnection(connectionString);
#region 执行简单SQL语句
public void connOpen()
{
if(conn.State==ConnectionState.Closed)
{
conn.Open();
}
}
public void connClose()
{
if(conn.State==ConnectionState.Open)
{
conn.Close();
}
}
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlCommand cmd = new SqlCommand(SQLString, conn))
{
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
SqlCommand cmd = new SqlCommand(SQLString, conn);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
SqlCommand cmd = new SqlCommand(strSQL, conn);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
//}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
using (SqlCommand cmd = new SqlCommand(SQLString, conn))
{
try
{
conn.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
conn.Close();
}
}
//}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader(此方法不能用,没有关闭连接)
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSQL)
{
//SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, conn);
try
{
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 从上面的ExecuteReader不能用,改成下面的方法,但打开连接是从此方法中进行,要从此方法外(调用处)关闭连接(我自己写的方法)
/// </summary>
/// <param name="strSQL"></param>
/// <param name="conn"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string strSQL,SqlConnection conn)
{
// SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, conn);
try
{
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
DataSet ds = new DataSet();
try
{
conn.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, conn);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
return ds;
//}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, conn, null, SQLString, cmdParms);
conn.Open();
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
// }
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
//using (SqlConnection conn = new SqlConnection(connectionString))
//{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
finally
{
conn.Close();
}
}
// }
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, conn, null, SQLString, cmdParms);
conn.Open();
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
conn.Close();
}
// }
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader(此方法不能用,没有关闭连接), 可以采用下面的方法,转成dt返回。
///// if (myReader.HasRows)
// {
// dt.Load(SqlDr);//读取SqlDataReader里的内容
// }
// this.dataGridView1.DataSource = dt;
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
{
// SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, conn, null, SQLString, cmdParms);
conn.Open();//连接没有关闭
SqlDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
return ds;
}
// }
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
//if (conn.State != ConnectionState.Open)
// conn.Open();//??
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
#region 存储过程操作
/// <summary>
/// 执行存储过程(此方法不能用,没有关闭连接)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader returnReader;
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.CommandType = CommandType.StoredProcedure;
returnReader = command.ExecuteReader();
return returnReader;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Close();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
return command;
}
/// <summary>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
//using (SqlConnection connection = new SqlConnection(connectionString))
//{
int result;
conn.Open();
SqlCommand command = BuildIntCommand(conn, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
conn.Close();
return result;
// }
}
/// <summary>
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand 对象实例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command
}
#endregion
#region 由Object取值
/// <summary>
/// 取得Int值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>int值</returns>
public static int GetInt(object obj)
{
if (obj.ToString() != "")
return int.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得byte值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>byte值</returns>
public static byte Getbyte(object obj)
{
if (obj.ToString() != "")
return byte.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 获得Long值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>long值</returns>
public static long GetLong(object obj)
{
if (obj.ToString() != "")
return long.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得Decimal值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>decimal值</returns>
public static decimal GetDecimal(object obj)
{
if (obj.ToString() != "")
return decimal.Parse(obj.ToString());
else
return 0;
}
/// <summary>
/// 取得Guid值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>Guid值</returns>
public static Guid GetGuid(object obj)
{
if (obj.ToString() != "")
return new Guid(obj.ToString());
else
return Guid.Empty;
}
/// <summary>
/// 取得DateTime值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>DateTime值</returns>
public static DateTime GetDateTime(object obj)
{
if (obj.ToString() != "")
return DateTime.Parse(obj.ToString());
else
return DateTime.MinValue;
}
/// <summary>
/// 取得bool值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>bool值</returns>
public static bool GetBool(object obj)
{
if (obj.ToString() == "1" || obj.ToString().ToLower() == "true")
return true;
else
return false;
}
/// <summary>
/// 取得byte[]值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>byte[]值</returns>
public static Byte[] GetByte(object obj)
{
if (obj.ToString() != "")
{
return (Byte[])obj;
}
else
return null;
}
/// <summary>
/// 取得string值
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>string值</returns>
public static string GetString(object obj)
{
return obj.ToString();
}
#endregion
#region 序列化与反序列化
/// <summary>
/// 序列化对象
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <returns>返回二进制</returns>
public static byte[] SerializeModel(Object obj)
{
if (obj != null)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] b;
binaryFormatter.Serialize(ms, obj);
ms.Position = 0;
b = new Byte[ms.Length];
ms.Read(b, 0, b.Length);
ms.Close();
return b;
}
else
return new byte[0];
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <param name="b">要反序列化的二进制</param>
/// <param name="SampleModel">Model的实体示例,New一个出来即可</param>
/// <returns>返回对象</returns>
public static object DeserializeModel(byte[] b, object SampleModel)
{
if (b == null || b.Length == 0)
return SampleModel;
else
{
object result = new object();
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
try
{
ms.Write(b, 0, b.Length);
ms.Position = 0;
result = binaryFormatter.Deserialize(ms);
ms.Close();
}
catch { }
return result;
}
}
#endregion
#region Model与XML互相转换
/// <summary>
/// Model转化为XML的方法
/// </summary>
/// <param name="model">要转化的Model</param>
/// <returns></returns>
public static string ModelToXML(object model)
{
XmlDocument xmldoc = new XmlDocument();
XmlElement ModelNode = xmldoc.CreateElement("Model");
xmldoc.AppendChild(ModelNode);
if (model != null)
{
foreach (PropertyInfo property in model.GetType().GetProperties())
{
XmlElement attribute = xmldoc.CreateElement(property.Name);
if (property.GetValue(model, null) != null)
attribute.InnerText = property.GetValue(model, null).ToString();
else
attribute.InnerText = "[Null]";
ModelNode.AppendChild(attribute);
}
}
return xmldoc.OuterXml;
}
/// <summary>
/// XML转化为Model的方法
/// </summary>
/// <param name="xml">要转化的XML</param>
/// <param name="SampleModel">Model的实体示例,New一个出来即可</param>
/// <returns></returns>
public static object XMLToModel(string xml, object SampleModel)
{
if (string.IsNullOrEmpty(xml))
return SampleModel;
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
XmlNodeList attributes = xmldoc.SelectSingleNode("Model").ChildNodes;
foreach (XmlNode node in attributes)
{
foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
{
if (node.Name == property.Name)
{
if (node.InnerText != "[Null]")
{
if (property.PropertyType == typeof(System.Guid))
property.SetValue(SampleModel, new Guid(node.InnerText), null);
else
property.SetValue(SampleModel, Convert.ChangeType(node.InnerText, property.PropertyType), null);
}
else
property.SetValue(SampleModel, null, null);
}
}
}
return SampleModel;
}
}
#endregion
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xjzdr/archive/2009/05/18/4196456.aspx