我现在的设置是一个3层应用程序: UI > BLL > DAL。每个层都被设置为一个单独的项目。UI是一个ASP.Net网站,BLL & DAL是类库项目。
我已经展示了来自我的每个层的一些示例代码。希望你们能批评我的应用程序设计,给我一些提示/指点,否则我做错了,引导我朝着正确的方向前进。谢谢!
public static object Get_UserId(string username)
{
ConnectionSettings connectionSettings = new ConnectionSettings();
SqlConnection sqlConnection = new SqlConnection(connectionSettings.ConnectionString);
string sql = String.Format("select UserId from Users where Username = '{0}'", username);
try
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
return sqlCommand.ExecuteScalar();
}
catch
{
throw new DALException("Unable to retreive User ID");
}
finally
{
sqlConnection.Close();
}
}的BLL方法
public static int GetUserId(string username)
{
try
{
int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());
return userId;
}
catch (Exception ex)
{
throw new BLLException(ex.Message);
}
}从UI:
try
{
int id = UserBLL.GetUserId("bobloblaw");
Response.Write(id);
}
catch (DALException dalEx)
{
Response.Write(dalEx.Message);
}
catch (BLLException bllEx)
{
Response.Write(bllEx.Message);
}发布于 2011-07-07 05:24:33
我将在您的代码/方法中更改的内容:
int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());
将使用:
int userId = new UserDAL().Get_UserId(username);
这些都是我脑子里最先想到的事情。
发布于 2011-08-06 03:16:30
我会第二次摆脱静态方法。我认为,数据访问应该是基于实例的。
但是,我的主要抓地力是,您没有使用参数化查询。此代码:
string sql = String.Format("select UserId from Users where Username = '{0}'", username);应:
string sql = @"select UserId from Users where Username = @username");
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
sqlCommand.Parameters.AddWithValue("@username", username);这样做将缓解使用string.Format(...)的SQL注入问题。我习惯于始终使用参数化查询,不管数据输入是否传递数据。没有理由不这样做。
另外,与使用finally不同,使用using语句来关闭和释放SqlCommand和SqlConnection之类的数据对象。
发布于 2011-08-06 08:18:35
DAL.Get_UserId中的所有异常并将它们替换为DALException是错误的。这样做,您将丢失有关原始异常的所有信息,例如堆栈跟踪,并且只保留消息(有时消息本身可能非常无用)。相反,创建更改BLLException构造函数以接受内部异常:公共BLLException (字符串消息,异常内部):base (消息,内部){}并相应抛出它:抛出新的BLLException (“错误获取用户ID",ex);然后可以通过InnerException属性访问内部异常。DALException,但它永远不会发生,因为业务层已经用BLLExceptions替换了它们。https://codereview.stackexchange.com/questions/3312
复制相似问题