Command.Parameters.Add无法正常工作? C#

时间:2016-05-30 22:27:32

标签: c# sql-server

我试图找出我的代码发生了什么,但我无法弄明白。我试图查询数据库以找出用户之前选择变量的信息。

我遇到的问题是它永远不会使用Parameters.AddWithValue方法中的值替换@client。我只是不确定我做错了什么。

selClient = comboBox1.SelectedItem.ToString();
string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = '@client';";

using (var conn = new SqlConnection("connection info"))
{
    SqlCommand cmd2 = new SqlCommand(cmdText, conn);
    {
        cmd2.Parameters.AddWithValue("@client", selClient);
        try
        {
            conn.Open();
            SqlDataReader rd = cmd2.ExecuteReader();
            while (rd.Read())
            {
                MessageBox.Show(String.Format("{0}", rd[0]));
            }
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }
}

请忽略所有通用变量,我是编程新手,并尝试在实际制作可用程序之前将其作为测试运行。

2 个答案:

答案 0 :(得分:4)

删除sql字符串中参数周围的单引号:

string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";

虽然我在这里,I'm not a fan of .AddWithValue(),您还可以进行其他一些改进:

selClient = comboBox1.SelectedItem.ToString();
string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";

//whenever I see a "cmd2", I wonder about "cmd1"... 
//  that you probably can and should get this into a single call into the database
using (var conn = new SqlConnection("connection info"))
using (var cmd2 = new SqlCommand(cmdText, conn))
{
    //guessing a parameter type/length here. Use exact type from your DB.
    cmd2.Parameters.Add("@client", SqlDbType.NVarChar,50).Value = selClient;
    conn.Open();

    // I prefer my try/catch block to happen up at least one level
    // Code at that level is usually better positioned to react to the exceptions

    var rd = cmd2.ExecuteReader();
    while (rd.Read())
    {
        MessageBox.Show(rd[0].ToString());
    }
    //The main point of a using block with SqlConnection is that is safely closes the connection for you
}

答案 1 :(得分:1)

您必须从参数''中删除引号@client

string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";