using System;
using System.Data;
using System.Data.SqlClient;
namespace Sqlhelp
{
/// <summary>
/// 数据库存储过程使用类
/// </summary>
public class SqlHelpProcdure
{
//全局SqlCommand对象实体
static SqlCommand _sqlCmd;
//全局SqlDataAdapter对象
static SqlDataAdapter _sqladapter;
//全局Sqlconnection对象
static SqlConnection sqlconn = Sqlhelp.Sql2005Help.getcon();
/// <summary>
/// 执行不带参数的存储过程,并返回受影响的行数
/// </summary>
/// <param name="ProcedureName">存储过程名称</param>
/// <returns>受影响的行数</returns>
public static int ExecuteWithOutPara(string ProcedureName)
{
_sqlCmd = new SqlCommand(ProcedureName, sqlconn);
//设置使用存储过程
_sqlCmd.CommandType = CommandType.StoredProcedure;
if (sqlconn.State != ConnectionState.Open)
{
sqlconn.Open();
}
int ret = -1;
try
{
ret = _sqlCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
//关闭连接
sqlconn.Close();
}
return ret;
}
/// <summary>
/// 执行带参数的存储过程,并返回受影响的行数
/// </summary>
/// <param name="ProcedureName">存储过程名称</param>
/// <param name="Parameters">参数集</param>
/// <returns>受影响的行数</returns>
public static int ExecuteWithPara(string ProcedureName, SqlParameter[] Parameters)
{
_sqlCmd = new SqlCommand(ProcedureName, sqlconn);
//设置使用存储过程
_sqlCmd.CommandType = CommandType.StoredProcedure;
//先清楚参数
_sqlCmd.Parameters.Clear();
_sqlCmd.Parameters.AddRange(Parameters);
if (sqlconn.State != ConnectionState.Open)
{
sqlconn.Open();
}
int ret = -1;
try
{
ret = _sqlCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
//关闭连接
sqlconn.Close();
}
return ret;
}
/// <summary>
/// 执行不带参数的存储过程查询,并返回查询结果
/// </summary>
/// <param name="ProcedureName">存储过程名称</param>
/// <returns>DataSet</returns>
public static DataSet ExecuteDataSetWithOutPara(string ProcedureName)
{
_sqladapter = new SqlDataAdapter();
DataSet dataset = new DataSet();
_sqlCmd = new SqlCommand(ProcedureName, sqlconn);
//设置使用存储过程
_sqlCmd.CommandType = CommandType.StoredProcedure;
if (sqlconn.State != ConnectionState.Open)
{
sqlconn.Open();
}
try
{
_sqladapter.SelectCommand = _sqlCmd;
_sqladapter.Fill(dataset);
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
//关闭连接
sqlconn.Close();
}
return dataset;
}
/// <summary>
/// 执行带参数的存储过程查询,并返回查询结果
/// </summary>
/// <param name="ProcedureName">存储过程名称</param>
/// <param name="Parameters">参数集</param>
/// <returns>DataSet</returns>
public static DataSet ExecuteDataSetWithPara(string ProcedureName, SqlParameter[] Parameters)
{
_sqladapter = new SqlDataAdapter();
DataSet dataset = new DataSet();
_sqlCmd = new SqlCommand(ProcedureName, sqlconn);
//设置使用存储过程
_sqlCmd.CommandType = CommandType.StoredProcedure;
//先清楚参数
_sqlCmd.Parameters.Clear();
_sqlCmd.Parameters.AddRange(Parameters);
if (sqlconn.State != ConnectionState.Open)
{
sqlconn.Open();
}
try
{
_sqladapter.SelectCommand = _sqlCmd;
_sqladapter.Fill(dataset);
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
//关闭连接
sqlconn.Close();
}
return dataset;
}
}
}