我有这个代码:
connection.Open();
string query = "UPDATE [dbo].[EmailPassword] SET HashedPassword = @hashedPassword, Salt = @salt, ForgotHisPassword = @forgotHisPassword where Email = @email";
SqlCommand command = new SqlCommand(query, connection);
string recoveredPassword = RandomPasswordGenerator.Generate();
PasswordHash passwordHash = new PasswordHash();
byte[] newHashedPassword = passwordHash.ComputeHash(recoveredPassword);
command.Parameters.AddWithValue("@hashedPassword", newHashedPassword);
command.Parameters.AddWithValue("@salt", passwordHash.saltAsString);
command.Parameters.AddWithValue("@forgotHisPassword", 1);
command.Parameters.AddWithValue("@email", TxtSendPasswordToEmail.Text);
command.ExecuteNonQuery();
我收到这个错误:
Must declare the scalar variable "@hashedPassword".
我一直在寻找解决方案,但找不到任何答案,非常感谢您的帮助!
编辑:终于找到问题了:
这是代码行之后的一行,起初我认为这与我的错误无关:
if (TableFunctions.querySucceeded(command))
函数的构建方式如下:
public static bool querySucceeded(string query, string strConnection)
{
SqlConnection connection = new SqlConnection(strConnection);
bool succeeded = false;
try
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
if (command.ExecuteScalar() != null)
{
succeeded = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return succeeded;
}
这意味着我只向它发送我想要执行的查询和连接,它应该执行它并在成功时返回但是查询不包含我添加到上一个命令的参数因此,该命令尝试执行上一个命令没有上一个命令的参数,这是失败的,并说:必须声明可变的@HashedPassword。 我是用debugging才找到的,也是费了点功夫,不过还是谢谢大家的支持!
最佳答案
你可以试试这段代码。假设您的数据库中的列是一个 varchar。如果不是,您可以轻松地将 SqlDbType
更改为您拥有的类型:
connection.Open();
string query = "UPDATE [dbo].[EmailPassword] SET HashedPassword = @hashedPassword, Salt = @salt, ForgotHisPassword = @forgotHisPassword where Email = @email";
SqlCommand command = new SqlCommand(query, connection);
string recoveredPassword = RandomPasswordGenerator.Generate();
PasswordHash passwordHash = new PasswordHash();
byte[] newHashedPassword = passwordHash.ComputeHash(recoveredPassword);
command.Parameters.Add("@hashedPassword", SqlDbType.Varchar); // you have to send the data type explicitely
command.Parameters["@hashedPassword"].Value = Encoding.ASCII.GetBytes(newHashedPassword);
command.Parameters.AddWithValue("@salt", passwordHash.saltAsString);
command.Parameters.AddWithValue("@forgotHisPassword", 1);
command.Parameters.AddWithValue("@email", TxtSendPasswordToEmail.Text);
command.ExecuteNonQuery();
关于c# - 更新表时必须声明标量变量@,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513738/