c# - Command.Parameters.Add 不起作用? C#

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

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

最佳答案

删除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
}

关于c# - Command.Parameters.Add 不起作用? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534353/

相关文章:

javascript - 从 Razor 代码中使用 javascript/jquery

c# - 使用泛型将类型信息传递给父类(super class)

sql where 针对两列

sql-server - SQL统计组数

c# - 使用 SQL Server 还是 C# 进行数据库设计?

php - PDO dblib nextRowset 不工作

c# - C++ CLI 结构到字节数组

c# - 如何在插入或更新表时检查表中是否已存在行或列

sql - SQL 表中未选择的列是否会减慢查询速度?

c# - 如何创建到主项目 MVC 到另一个项目 MVC 的路由?