gpt4 book ai didi

c# - 如何从数据库中取值?必须声明标量变量 "@ID1"

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:02 24 4
gpt4 key购买 nike

  public partial class Form3 : Form
{
string var;
int ID1;

private void button1_Click(object sender, EventArgs e)
{
ID1 = int.Parse(textBox1.Text);
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\asp\Desktop\DatabasesPractice\DatabasesPractice\soccer.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand dataCommand = new SqlCommand("SELECT Name FROM team WHERE ID = @ID1", cn);

cn.Open();
var = Convert.ToString(dataCommand.ExecuteScalar());
label3.Text = var;

}
}

它给了我一个错误,说我必须声明标量变量 @ID,我到处搜索,但无法为我的具体情况找到解决方案。

感谢大家的帮助!你的解决方案有效:D

最佳答案

public partial class Form3 : Form 
{
string var;
int ID1;

private void button1_Click(object sender, EventArgs e)
{
ID1 = int.Parse(textBox1.Text);
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\asp\Desktop\DatabasesPractice\DatabasesPractice\soccer.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand dataCommand = new SqlCommand("SELECT Name FROM team WHERE ID = @ID1", cn);
dataCommand.Parameters.AddWithValue("@ID1", ID1); // this is the new line of code

cn.Open();
var = Convert.ToString(dataCommand.ExecuteScalar());
label3.Text = var;

}

}

见上文,我添加了 dataCommand.Parameters.AddWithValue("@ID1", ID1);。它所做的是为您的 SQL 查询定义您的参数并将值传递给它。我假设您希望变量 ID1 成为您的 SQL 参数 @ID1 的值。

关于c# - 如何从数据库中取值?必须声明标量变量 "@ID1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8342555/

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