下面是一个封装了的ADO.NET连接数据库的模块,可以执行几乎所有的存储过程,稍做修改便可执行所有的SQL Command的单语句命令:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DBModules
{
/**//// <summary>
/// 数据库访问辅助类,该类中都是静态的方法,以更方便的调用存储过程
/// </summary>
public sealed class SqlHelper
{
/**//// <summary>
/// 这里用私有函数,防止实例化该类
/// </summary>
private SqlHelper()
{
}
/**//// <summary>
/// 获取数据库连接字符串
/// </summary>
public static string connectionString
{
get{ return ConfigurationSettings.AppSettings["connectString"];}
}
/**//// <summary>
/// Private routine allowed only by this base class, it automates the task
/// of building a SqlCommand object designed to obtain a return value from
/// the stored procedure.
/// </summary>
/// <param name="storedProcName">Name of the stored procedure in the DB, eg. sp_DoTask</param>
/// <param name="parameters">Array of IDataParameter objects containing parameters to the stored proc</param>
/// <returns>Newly instantiated SqlCommand instance</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, /**//* Size */
ParameterDirection.ReturnValue,
false, /**//* is nullable */
0, /**//* byte precision */
0, /**//* byte scale */
string.Empty,
DataRowVersion.Default,
null ));
return command;