使用C#的新用户,我想更新sql数据库中的现有数据。我明白DataRow dr = dTable.NewRow();实际上添加了一个新行但我希望使用文本框中的数据更新所选行的命令。提前谢谢。
MySqlDataAdapter dAdapter = new MySqlDataAdapter("SELECT * FROM myDatabase WHERE username ='" + txtUserName.Text + "'", myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
if (dTable.Rows.Count == 0)
{
DialogResult drError;
drError = MessageBox.Show("That user name does not exist, please create a user.", "User name does not exist", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (drError == DialogResult.Yes)
{
this.Close();
}
}
else if (dTable.Rows.Count == 1)
{
DataRow dr = dTable.NewRow();
dr["day1consumed"] = Convert.ToInt32(txtCCDay1.Text);
dr["day1burned"] = Convert.ToInt32(txtCBDay1.Text);
dr["day2consumed"] = Convert.ToInt32(txtCCDay2.Text);
dr["day2burned"] = Convert.ToInt32(txtCBDay2.Text);
dr["day3consumed"] = Convert.ToInt32(txtCCDay3.Text);
dr["day3burned"] = Convert.ToInt32(txtCBDay3.Text);
dr["day4consumed"] = Convert.ToInt32(txtCCDay4.Text);
dr["day4burned"] = Convert.ToInt32(txtCBDay4.Text);
dr["day5consumed"] = Convert.ToInt32(txtCCDay5.Text);
dr["day5burned"] = Convert.ToInt32(txtCBDay5.Text);
dr["day6consumed"] = Convert.ToInt32(txtCCDay6.Text);
dr["day6burned"] = Convert.ToInt32(txtCBDay6.Text);
dr["day7consumed"] = Convert.ToInt32(txtCCDay7.Text);
dr["day7burned"] = Convert.ToInt32(txtCBDay7.Text);
dTable.Rows.Add(dr);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dAdapter);
int iRowsAffected = dAdapter.Update(dTable);
dAdapter.Dispose();
DialogResult drReply;
drReply = MessageBox.Show("Your data has been saved", "Record updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (drReply == DialogResult.Yes)
{
this.Close();
}
else
{
MessageBox.Show("Error saving data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
答案 0 :(得分:2)
您的实际代码会添加一个新行,而您需要获取SELECT命令检索到的实际行并将其更改为新值。
所以你只需改变这一行
DataRow dr = dTable.NewRow();
in
DataRow dr = dtTable.Rows[0];
并开始更新值 在更新结束时,您不需要将行添加到表的实际行集合(它已经存在并且您已对其进行了修改)。
因此应删除此行
// dTable.Rows.Add(dr);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dAdapter);
int iRowsAffected = dAdapter.Update(dTable);
....
说,我想指出SELECT命令文本中的一个严重问题。您使用字符串连接来形成命令,这是一个众所周知的安全问题,称为 Sql Injection 。如果要获取用户类型值并查询数据库,则需要使用parameterized query
string cmdText = "SELECT * FROM myDatabase WHERE username =@name"
MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmdText,myConn);
dAdapter.SelectCommand.Parameters.Add("@name", MySqlDbType.VarChar).Value = txtUserName.Text
.....