c#使用"using"中的参数执行SqlCommand代码块 [英] c# execute SqlCommand with Parameters in "using" code block

查看:79
本文介绍了c#使用"using"中的参数执行SqlCommand代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用"代码块执行SQL命令,但似乎无法使其与Parameters一起使用.我收到错误消息:当前上下文中不存在参数",有人可以解决此问题吗?这是我的代码:

I am attempting to execute an SQL Command through a 'using' code block, but can't seem to get it to work with Parameters. I get the error: 'Parameters does not exist in the current context', does anyone have a possible solution for this problem? Heres My code:

DataTable dt = new DataTable();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand(" SELECT FName" +
                                        " FROM EmployeeTable " +
                                        " WHERE EmployeeId = @empId",
                                        con)
                                        {
                                            Parameters.Add(new SqlParameter("@empId",empId))
                                        })
        {
            try
            {
                   con.open();
                   dt.Load(cmd.ExecuteReader());
            }
            catch(Exception ex)
            {
                 //(snip) Log Exceptions
            }
        }
        return dt;

推荐答案

请勿为此使用构造函数初始化.

Don't use constructor initialization for this.

DataTable dt = new DataTable();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand(" SELECT FName" +
                                        " FROM EmployeeTable " +
                                        " WHERE EmployeeId = @empId",
                                        con))
{
    cmd.Parameters.Add(new SqlParameter("@empId",empId));
    try
    {
           con.open();
           dt.Load(cmd.ExecuteReader());
    }
    catch(Exception) //BAD BAD BAD!!! Why are you doing this!
    {
    }
}
return dt;

为什么还要捕获所有异常并将它们丢弃,这是一件可怕的事情.如果您有异常,则认为会很常见,请首先查看是否可以重构代码以检查导致该输入值的输入值,而根本不会抛出该输入值(甚至可能抛出 ArgumentException ),如果不能这样做,请检查该特定例外,而不是所有可能的例外.

Also why are you catching all exceptions and throwing them away, this is a horrible thing to. If you have a exception you think is going to be common first see if you can refactor your code to check the for the input values that would cause it and not have it thrown at all (perhaps even throw an ArgumentException of your own), and if you can't do that then check for that specific exception, not every possible one.

这篇关于c#使用"using"中的参数执行SqlCommand代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆