gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:40:58 25 4
gpt4 key购买 nike

我试图弄清楚我的代码发生了什么,但我无法弄清楚。我正在尝试查询数据库以查找用户先前选择变量的信息。

我遇到的问题是它永远不会用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com