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();
}web

}
/// <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) ;
}
}sql

相關文章
相關標籤/搜索