添加参数给出错误 - 必须声明标量变量"@variable"

use*_*417 0 c# sql-server

我正在使用以下代码尝试从SQL Server数据库表返回结果

 MySqlCommand.CommandText = "SELECT * FROM dbo.MyTable WHERE [My Id] = @variable";
 MySqlCommand.Parameters.Add("@variable", SqlDbType.Int).Value = GetsMyId(this.Mycombobox.SelectedItem.ToString());
Run Code Online (Sandbox Code Playgroud)

我尝试过使用.Parameters.AddWithValue("@ variable",value); 但我已经了解了这些缺点并决定使用这种方法.代码既不适用也不适用.返回错误'必须声明标量变量'@variable"'

我不确定我错过了什么,因为我有一个可以实现类似功能的工作版本.在这种情况下,上下文不同,此代码遵循原始

//Line that fixes it (added at this point) for anyone else that encounters the issue.
//MySqlConnection.connection = MyConnection;

System.Data.SqlClient.SqlDataAdapter Adapter = new System.Data.SqlClient.SqlDataAdapter(MySqlCommand.CommandText, conn.ConnectionString);

DataTable MyDataTable = new DataTable();

Adapter.Fill(MyDataTable);
Run Code Online (Sandbox Code Playgroud)

在最后一行抛出错误 Adapter.Fill(MyDataTable)

有什么愚蠢的我错过了或者是否存在一些我不知道添加参数值和DataAdapters之间的不兼容性?

Shn*_*ugo 5

在这一行

new System.Data.SqlClient.SqlDataAdapter(MySqlCommand.CommandText, conn.ConnectionString)
Run Code Online (Sandbox Code Playgroud)

...你传入的是CommandText,而不是对象"MySqlCommand"

SqlDataAdapter有一个构造函数取一个命令对象,以及一个以字符串...