WPF新手。我想编辑文本框中显示的数据库行的值。目前我收到一个错误:“ExecuteNonQuery:Connection属性尚未初始化”。当我删除where子句时,所有行都会更新,而不仅仅是所选项。
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'");
cmd.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:0)
您尚未设置SqlCommand
的{{3}}属性。所以命令不知道连接的位置。使用SqlCommand
中的Connection
或将其设置为此
cmd.Connection = sc;
答案 1 :(得分:0)
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'",sc); // add connection here
您还应该使用参数化查询或存储过程来阻止SQL注入攻击。
SqlCommand cmd = new SqlCommand("Update Rewards set Name = @name, Cost= @cost where Name = @name ,sc);
cmd.Parameters.AddWithValue("@name", Convert.ToString(this.txtName.Text)); and so on
答案 2 :(得分:0)
我希望这就是你所需要的:)复制粘贴这个。祝你好运,兄弟! :)如果您有疑问,请问,如果我知道LOL,我会回答:)
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
sql = "UPDATE REWARDS SET Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'WHERE Name = '" + this.txtName.Text +"'");
SqlCommand command = new SqlCommand(sql, con);
command.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}