我试图弄清楚我的代码发生了什么,但我无法弄清楚。我正在尝试查询数据库以查找用户先前选择变量的信息。
我遇到的问题是它永远不会用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;";
当我在这里时,我不是
.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
}
您必须从参数
''
中删除引号 @client
:
string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";