2016-05-30 51 views
2

我想弄清楚我的代码是怎么回事,我无法弄清楚。我试图查询数据库以找出用户以前选择变量的信息。Command.Parameters.Add不工作? C#

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

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(); 
     } 
    } 
} 

请忽略所有的通用变量的,我是新来编程,我试图做这一切的试运行之前,我确实做一个可用的程序。

回答

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 
} 
+0

从第二个示例中删除引号。 –

+0

明白了,谢谢:) –

1

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

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