.NET 中数据库调用的代码片段改进

发布于 2024-12-25 00:00:59 字数 1606 浏览 6 评论 0原文

我可以获得以下代码的问题列表以及修复方法吗?

 string ProgramID = HttpContext.Current.Session[CommonFunctions.myNGconnectSessionVars.ProgramId].ToString();
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            DataSet ds = new DataSet();
            try
            {
                cmd.Connection = con;
                cmd.CommandTimeout = 900;
                cmd.CommandText = "dsb_GetSubscriptionDetailsForSubscriber_ForValidations";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@GPCustomerID", strGPCustomerID);
                cmd.Parameters.AddWithValue("@UserName", strUserName);
                cmd.Parameters.AddWithValue("@ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
                //code changed by sushma 3/22/2011 as new tab added for reach
                //cmd.Parameters.AddWithValue("@ProgramID", CommonFunctions.ProgramID);
                cmd.Parameters.AddWithValue("@ProgramID", ProgramID);
                cmd.Parameters.AddWithValue("@IsTeacher", blnIsTeacher);
                // cmd.CommandTimeout = 0;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }

            return ds;

Can I get a list of issues with the code below, and fixes?

 string ProgramID = HttpContext.Current.Session[CommonFunctions.myNGconnectSessionVars.ProgramId].ToString();
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            DataSet ds = new DataSet();
            try
            {
                cmd.Connection = con;
                cmd.CommandTimeout = 900;
                cmd.CommandText = "dsb_GetSubscriptionDetailsForSubscriber_ForValidations";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@GPCustomerID", strGPCustomerID);
                cmd.Parameters.AddWithValue("@UserName", strUserName);
                cmd.Parameters.AddWithValue("@ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
                //code changed by sushma 3/22/2011 as new tab added for reach
                //cmd.Parameters.AddWithValue("@ProgramID", CommonFunctions.ProgramID);
                cmd.Parameters.AddWithValue("@ProgramID", ProgramID);
                cmd.Parameters.AddWithValue("@IsTeacher", blnIsTeacher);
                // cmd.CommandTimeout = 0;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }

            return ds;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

习ぎ惯性依靠 2025-01-01 00:00:59

我看到的最大问题是您没有处理一次性对象,例如连接、命令、适配器……因此,如果出现异常,您可能会泄漏资源。要修复您的代码,请将所有一次性资源包装在 using 语句中:

using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString()))
using (SqlCommand cmd = con.CreateCommand())
{
    con.Open();
    cmd.CommandTimeout = 900;
    cmd.CommandText = "dsb_GetSubscriptionDetailsForSubscriber_ForValidations";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@GPCustomerID", strGPCustomerID);
    cmd.Parameters.AddWithValue("@UserName", strUserName);
    cmd.Parameters.AddWithValue("@ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
}

我还删除了 try/catch 块,因为您似乎没有在 中执行任何有用的操作>catch 语句除了改变堆栈跟踪之外,这是不好的。

The biggest issue that I can see is that you are not disposing disposable objects such as connections, commands, adapters, ... so in case of exception you might leak resources. To fix your code wrap all disposable resources in using statements:

using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString()))
using (SqlCommand cmd = con.CreateCommand())
{
    con.Open();
    cmd.CommandTimeout = 900;
    cmd.CommandText = "dsb_GetSubscriptionDetailsForSubscriber_ForValidations";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@GPCustomerID", strGPCustomerID);
    cmd.Parameters.AddWithValue("@UserName", strUserName);
    cmd.Parameters.AddWithValue("@ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
}

I have also removed the try/catch block as you don't seem to be doing anything useful in the catch statement other than altering the stack trace which is bad.

抚笙 2025-01-01 00:00:59

以下是一些直接改进

使用 using 语句而不是 try/finally 进行连接管理

使用 throw 而不是 throw ex 重新抛出异常,更好的是,您可以删除 catch 并重新抛出。

无需在刚刚实例化的命令上调用 Parameters.Clear

最后,如果您打算进行大量数据库工作,我建议您考虑使用轻量级 ORM。

Here are some immediate improvements

Use using statement rather than try/finally for the connection management

Use throw and not throw ex to re-throw the exception, better yet you can just remove the catch and re-throw

There is no need to call Parameters.Clear on the command that you just instantiated.

And finally, if you are going to do a lot of DB work, I would suggest you look at using a lightweight ORM.

彡翼 2025-01-01 00:00:59

除了:

ConfigurationManager.AppSettings["服务器名称"]

调用数百次时可能会有点慢并且

str用户名

您是否因为在过去 10 年里一直被强烈劝阻而使用匈牙利表示法而被解雇?

还有:

cmd.CommandTimeout = 900;

啊 - 不。 900秒?你认为你到底需要做什么?

cmd.Parameters.Clear();

是的。就像新对象需要这样。

DataSet ds = new DataSet();

我解雇了所有使用数据集的人;)除了在通用查询工具中,该工具直接指向用户界面。

不是很多——好吧,而且我们并不真正在这里做作业复习。我宁愿不使用 useles try/catch 而是使用 USING 语句。

Except:

ConfigurationManager.AppSettings["ServerName"]

Maybe be a little slow when called hundreds of times and

strUserName

you are fired for using hungarian notation when strondly discouraged for the last 10 years?

And that:

cmd.CommandTimeout = 900;

Ah - no. 900 seconds? What the heck do you think you do there that needs that?

cmd.Parameters.Clear();

Yeah. Like this is needed on a new object.

DataSet ds = new DataSet();

And i fire anyone in general who uses datasets ;) Except in a general query tool where that thing geos straight to the UI.

Not a lot - well, also that we dont realyl do homework reviews here. And I rather would not use a useles try/catch instead going to USING statements.

毁梦 2025-01-01 00:00:59

它主要是一个构造,我想评论一下:

  • 不要使用 throw ex - 它会改变 ex 的 StackTrace。请改用throw;
  • 留下catch-Block。您可以简单地使用 try-finally
  • 使用 concmd 两个 using 语句

其他一些要点:

  • 使用不言自明的变量名称
  • 将更改历史记录放入版本控制系统中(并且从注释中删除它!)
  • 让源代码控制系统处理旧代码,而不是简单地将其注释掉
  • 缓存您的数据库连接
  • 使用SqlConnection.CreateCommand

It's mainly one construct, I want to comment on:

  • Don't use throw ex - it will alter the StackTrace of ex. Use throw; instead.
  • Leave away the catch-Block. You can simply use try-finally
  • Use two using statements for con and cmd

Some other points:

  • use self-explanatory variable names
  • Put the change history into the version control system (and remove it from the comments!)
  • Let the source control system handle old code instead of simply commenting it out
  • Cache your DB-connection
  • Use SqlConnection.CreateCommand
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文