使用更新查询c#时丢失信息
本文关键字:信息 更新 查询 | 更新日期: 2023-09-27 18:26:08
嗨,我正试图使用更新查询来更新一列甚至整行,但当我只更新某一列时,我会得到"一个或多个所需参数没有给定值"。如何使用该代码同时更新列和行?
这是我的代码:
protected void updateButtn_Click(object sender, EventArgs e)
{
using (var myConnection = GetConnection())
{
myConnection.Open();
// You should be using a parameterized query here
using (var cmd = new OleDbCommand("Update client set username = ?, [name] = ?, surname = ?, [email] = ?, [password] = ? where id = ?", myConnection))
{
cmd.Parameters.AddWithValue("username", txt_uname.Text);
cmd.Parameters.AddWithValue("[name]", txt_name.Text);
cmd.Parameters.AddWithValue("surname", txt_sname.Text);
cmd.Parameters.AddWithValue("[email]", txt_email.Text);
cmd.Parameters.AddWithValue("[password]", txt_password.Text);
cmd.Parameters.AddWithValue("[id]", txt_id.Text);
cmd.ExecuteNonQuery();
} myConnection.Close();
}
}
您忘记为[health issues]
添加一个参数,这就是错误对您大喊大叫的缺失列。
protected void clientUpdate_Click(object sender, EventArgs e)
{
using (var myConnection = GetConnection())
{
myConnection.Open();
using (var cmd = new OleDbCommand("Update client set [name] = ?, surname = ?, [date of birth] = ?, [health issues] = ?, [yoga experience] = ?, [email] = ?, [phone number] = ?, [home address] = ?, [password] = ? where id = ?", myConnection))
{
cmd.Parameters.AddWithValue("[name]", txt_name.Text);
cmd.Parameters.AddWithValue("surname", txt_sname.Text);
cmd.Parameters.AddWithValue("[date of birth]", txt_dob.Text);
cmd.Parameters.AddWithValue("[health issues]", txt_HealthIssues.Text); '' <---- This was missing.
cmd.Parameters.AddWithValue("[yoga experience]", txt_exp.Text);
cmd.Parameters.AddWithValue("[email]", txt_email.Text);
cmd.Parameters.AddWithValue("[phone number]", txt_phone.Text);
cmd.Parameters.AddWithValue("[home address]", txt_address.Text);
cmd.Parameters.AddWithValue("[password]", txt_password.Text);
cmd.Parameters.AddWithValue("id", txt_id.Text);
cmd.ExecuteNonQuery();
}
}
}
如果只想更新1列,则需要编写一个不包含查询中其他参数的新查询。传统上,人们会使用像实体框架这样的ORM库来简化这一点。你需要检查一下,看看你是否能找到一个与OleDb连接对象兼容的ORM图书馆。
此外,如果你不使用ORM,你可能不想使用AddWithValue,它必须假设你的代码是什么数据类型,有时你可能会遇到很大的性能问题,因为它猜测错误时没有正确使用索引。
问题是,如果其中一个文本框为空,则将提供一个null值作为参数。这就是为什么您会得到无值给定错误。
你可以通过以下操作来解决这个问题:
cmd.Parameters.AddWithValue("[name]", string.IsNullOrEmpty(txt_name.Text) ?
(object)DBNull.Value : txt_name.Text);
如果文本框为空,则会将列值设置为null。
如果你只想更新已经填写的字段,你可以这样做:
string cmd = "update blah set ";
bool shouldUpdate = false;
if (!string.IsNullOrEmpty(name_textbox))
{
shouldUpdate = true;
cmd += "name = ?,"; don't add the comma for the last one
command.Parameters.AddWithValue("name",name_textbox.Text);
}
... do this for each of your text boxes
if (shouldUpdate)
{
cmd += "where id = ?";
command.Parameters.AddWithValue("id",id);
command.ExecuteNonQuery();
}
但这有点难看,我建议在加载页面时确保文本框中填充了当前数据。