简体   繁体   English

c#在“使用”代码块中使用参数执行SqlCommand

[英]c# execute SqlCommand with Parameters in “using” code block

I am attempting to execute an SQL Command through a 'using' code block, but can't seem to get it to work with Parameters. 我试图通过“使用”代码块执行SQL命令,但似乎无法使其与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;

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. 如果您有一个异常,则认为会很常见,首先请查看是否可以重构代码以检查导致该输入的值,而根本不会抛出该输入值(甚至可能抛出您自己的ArgumentException ),并且如果您不能这样做,请检查该特定例外,而不是所有可能的例外。

It is impossible to use object initializer for anything other than property assignment, so you should rewrite your code like this (only relevant part here): 除了属性分配以外,不可能将对象初始化程序用于任何其他事情,因此您应该像这样重写代码(此处仅相关部分):

...
using (var cmd = new SqlCommand(" SELECT FName" +
                                        " FROM EmployeeTable " +
                                        " WHERE EmployeeId = @empId",
                                        con))
{
    cmd.Parameters.Add(new SqlParameter("@empId", empId));
...

Your second using statement closes before the try catch. 您的第二个using语句在try catch之前关闭。 Therefore once the try catch is reached the using block has already been closed. 因此,一旦达到try catch,使用块就已经关闭。 The parameters are therefore in the incorrect scope. 因此,参数在错误的范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM