以下是保存按钮事件处理程序:
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
con.Open();
if (txtFN.Text != "" && txtMN.Text != "" && txtLN.Text != "" && txtAge.Text != "" && txtReligion.Text != "" && cmbGender.Text != "" && dateTimePicker1.Text != "" && cmbGrade.Text != "" && cmbStrands.Text != "" && txtPlaceBirth.Text != "" && txtHomeAddress.Text != "" && txtNameLastSchool.Text != "" && txtAddressLastSchool.Text != "")
{
cmd = new MySqlCommand("UPDATE tbluser set FirstName, MiddleName, LastName, Age, Religion, Gender, BirthDay, Grade, Strand, PlaceBirth, HomeAddress, NameLastSchool, AddressLastSchool) values (@fname, @mname, @Lname, @Age, @Religion, @Gender, @Birthday, @Grade, @Strand, @PlaceBirth, @HomeAddress, @NameLastSchool, @AddressLastSchool", con);
cmd.Parameters.AddWithValue("@fname", txtFN.Text);
cmd.Parameters.AddWithValue("@Mname", txtMN.Text);
cmd.Parameters.AddWithValue("@Lname", txtLN.Text);
cmd.Parameters.AddWithValue("@Age", txtAge.Text);
cmd.Parameters.AddWithValue("@Religion", txtReligion.Text);
cmd.Parameters.AddWithValue("@Gender", cmbGender.Text);
cmd.Parameters.AddWithValue("@Birthday", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("@Grade", cmbGrade.Text);
cmd.Parameters.AddWithValue("@Strand", cmbStrands.Text);
cmd.Parameters.AddWithValue("@PlaceBirth", txtPlaceBirth.Text);
cmd.Parameters.AddWithValue("@HomeAddress", txtHomeAddress.Text);
cmd.Parameters.AddWithValue("@NameLastSchool", txtNameLastSchool.Text);
cmd.Parameters.AddWithValue("@AddressLastSchool", txtAddressLastSchool.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Updated Successfully");
MessageBox.Show("Please Select Record to Update");
}
}
但是代码没有按照我的意图运作。 我错过了什么?
答案 0 :(得分:1)
UPDATE
DML命令使用以下语法:
UPDATE [table_name] SET [assignment_list]
或者如果您想更新现有记录:
UPDATE [table_name] SET [assignment_list] WHERE [condition]
因此,正确的语法应如下所示:
cmd = new MySqlCommand("UPDATE tbluser SET FirstName = @fname, MiddleName = @mname, LastName = @Lname, Age = @Age, Religion = @Religion, Gender = @Gender, BirthDay = @Birthday, Grade = @Grade, Strand = @Strand, PlaceBirth = @PlaceBirth, HomeAddress = @HomeAddress, NameLastSchool = @NameLastSchool, AddressLastSchool = @AddressLastSchool WHERE UserId = @UserId", con);
cmd.Parameters.AddWithValue("@fname", txtFN.Text);
// other parameters
cmd.Parameters.AddWithValue("@UserId", txtID.Text); // example for assigning record ID
cmd.ExecuteNonQuery();
呈现的查询看起来像是尝试进行INSERT
查询,但由于语法不正确而导致异常。