Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

sql - 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. 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...