还在为每次都要写数据库连接发愁吗? 楼主共享DBhelper类一个! 支持ASP.NET,C#
[C#] 纯文本查看 复制代码 private static readonly string ConString = ConfigurationManager.ConnectionStrings["MyBookShop"].ToString();
public SqlConnection connection = null;
public SqlCommand command = null;
public SqlDataReader reader = null;
public DataSet ds = null;
/// <summary>
/// 受影响行数
/// </summary>
/// <param name="sp"></param>
/// <param name="parameter"></param>
/// <returns></returns>
public int GetExecuteNonQuery(string sp, SqlParameter[] parameter)
{
connection = new SqlConnection(ConString);
connection.Open();
command = new SqlCommand(sp,connection);
if(parameter!=null)
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddRange(parameter);
}
int Num = command.ExecuteNonQuery();
connection.Close();
return Num;
}
/// <summary>
/// 第一行第一列
/// </summary>
/// <param name="sp"></param>
/// <param name="parameter"></param>
/// <returns></returns>
public int GetExecuteScalar(string sp, SqlParameter[] parameter)
{
connection = new SqlConnection(ConString);
connection.Open();
command = new SqlCommand(sp, connection);
if (parameter != null)
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddRange(parameter);
}
int Num =Convert.ToInt32(command.ExecuteScalar());
connection.Close();
return Num;
}
/// <summary>
/// 查询
/// </summary>
/// <param name="sp"></param>
/// <param name="paramemter"></param>
/// <returns></returns>
public SqlDataReader GetExecuteReader(string sp, SqlParameter[] paramemter)
{
connection = new SqlConnection(ConString);
connection.Open();
command = new SqlCommand(sp,connection);
if (paramemter != null)
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddRange(paramemter);
}
reader = command.ExecuteReader();
return reader;
}
public void Close()
{
if(connection!=null)
{
connection.Close();
}
if(reader!=null)
{
reader.Close();
}
}
/// <summary>
/// 返回DataSet
/// </summary>
/// <param name="sp"></param>
/// <param name="parameter"></param>
/// <returns></returns>
public DataSet GetDataSet(string sp , SqlParameter[] parameter)
{
ds = new DataSet();
connection = new SqlConnection(ConString);
connection.Open();
if (parameter != null)
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddRange(parameter);
}
SqlDataAdapter da = new SqlDataAdapter(sp,connection);
da.Fill(ds);
return ds;
}
|