sqlhelper简化版

public class sqlhelper
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
/// common uses of SqlClient
/// </summary>
public sealed class SqlHelper
{
//获取数据库连接字符串,属于静态变量且只读,项目中所有文档可以直接使用,但不能修改
public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["stdInfoConnectionString"].ConnectionString;

/// <summary>
/// 执行一个不需要返回值的sqlCommand命了,通过制定专用的连接字符串
/// 使用参数数组形式提供参数
/// </summary>
/// <remarks>
public static int ExecuteNonquery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd
= new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
//通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}

public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd
= new SqlCommand();
SqlConnection conn
= new SqlConnection(connectionString);
try
{
PrepareCommand(cmd, conn,
null, cmdType, cmdText, commandParameters);
SqlDataReader rdr
= cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd
= new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn,
null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;

}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, 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
= cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}



}
}

}

posted on 2011-06-09 10:29  LkSh  阅读(521)  评论(0编辑  收藏  举报

导航