SQLHelper类
作者:互联网
private static string constr = ConfigurationManager.ConnectionStrings["constr"].ToString();//连接字符串从web.config或者app.config,使用时注意引用System.Configuation
/// <summary>
/// 通用非查询方法
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteNonQuery(string sql)
{
SqlConnection sqlConnection = new SqlConnection(constr);//
SqlCommand sqlCommand = new SqlCommand(sql,sqlConnection);
try
{
sqlConnection.Open();
return sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
//捕获异常
throw new Exception("执行public int ExecuteNonQuery(string sql)方法发生异常" + ex.Message);
}
finally
{
sqlConnection.Close();
}
}
/// <summary>
/// 通用查询返回单个对象方法
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object GetExcuteScalar(string sql)
{
SqlConnection sqlConnection = new SqlConnection(constr);
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
try
{
sqlConnection.Open();
return sqlCommand.ExecuteScalar();
}
catch (Exception ex)
{
//捕获异常
throw new Exception("执行public object GetExcuteScalar(string sql)方法发生异常" + ex.Message);
}
finally
{
sqlConnection.Close();
}
}
/// <summary>
/// 通用查询方法返回SQLDataReader结果集
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public SqlDataReader GetExecuteReader(string sql)
{
SqlConnection sqlConnection = new SqlConnection(constr);
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
try
{
sqlConnection.Open();
return reader;
}
catch (Exception ex)
{
//捕获操作异常
throw new Exception("执行public SqlDataReader GetExecuteReader(string sql)方法发生异常" + ex.Message) ;
}
}
标签:string,sql,SqlConnection,ex,new,sqlConnection,SQLHelper 来源: https://www.cnblogs.com/NETer-P/p/12919470.html