我有一个带有2个表NewSubject和NewStudentInfo的Access数据库,它们也有关系。我想更新NewSubject中的字段,但它不起作用。该怎么办?谢谢。见下图。
2个不同的更新代码但不起作用。
如果我将此代码与Concatenate一起使用,MessageBox将弹出并显示“已更新”,但显然它不会更新数据库。我会在证明代码后附上一些图片。
string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\Betches\MiniThesis\MACInfo\MACInfo\bin\Debug\Database\MasterList.accdb";
string query = "UPDATE NewSubjects SET StudentID = '" + maskedTextBox1.Text + "',SubjectCode = '" + TextBoxSubjectCode.Text + "',SubjectDescription = '" + TextBoxSubjectDesc.Text + "',Unit = '" + TextBoxUnit.Text + "',SubjectGrade = '" + TextBoxSubjectGrade.Text + "',Course = '" + TextBoxCourse.Text + "',AcademicYear = '" + TextBoxYear.Text + "',Semester = '" + TextBoxSemester.Text + "' WHERE StudentID = '" + maskedTextBox1.Text + "';";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command1 = new OleDbCommand(query, connection);
OleDbDataReader myReader;
try
{
connection.Open();
myReader = command1.ExecuteReader();
MessageBox.Show("Updated!","MACInfo",MessageBoxButtons.OK,MessageBoxIcon.Information);
Loader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
注意:我正在尝试更新第一行,第3列是SubjectCode。 Concat Code Image Proof CLICK ME! CLICK ME FOR Database
如果我要使用Parameters.AddWithValue,它将不会更新数据库,它将显示消息框说“更新不成功!”但代码没有错误。页脚上附有图像以供证明。
OleDbConnection conn = new OleDbConnection(@"Provider=M1icrosoft.ACE.OLEDB.12.0;Data Source=D:\Projects\Betches\MiniThesis\MACInfo\MACInfo\bin\Debug\Database\MasterList.accdb");
command = conn.CreateCommand();
command.CommandText = @"UPDATE NewSubjects SET [StudentID] = @Sid,
[SubjectCode] = @Sc,
[SubjectDescription] = @Sd,
[Unit] = @Un,
[SubjectGrade] = @Sg,
[Course] = @Crs,
[AcademicYear] = @Yr,
[Semester] = @Sem WHERE [StudentID] = @Sid";
command.Parameters.AddWithValue("@Sid", maskedTextBox1.Text);
command.Parameters.AddWithValue("@SC", TextBoxSubjectCode.Text);
command.Parameters.AddWithValue("@Sd", TextBoxSubjectDesc.Text);
command.Parameters.AddWithValue("@Un", TextBoxUnit.Text);
command.Parameters.AddWithValue("@Sg", TextBoxSubjectGrade.Text);
command.Parameters.AddWithValue("@Crs", TextBoxCourse.Text);
command.Parameters.AddWithValue("@Yr", TextBoxYear.Text);
command.Parameters.AddWithValue("@Sem", TextBoxSemester.Text);
conn.Open();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected != 0)
{
MessageBox.Show("Update Successful!", "MACInfo", MessageBoxButtons.OK, MessageBoxIcon.Information);
Loader();
TextBoxSubjectCode.Enabled = false;
TextBoxSubjectDesc.Enabled = false;
TextBoxUnit.Enabled = false;
TextBoxSubjectGrade.Enabled = false;
TextBoxCourse.Enabled = false;
TextBoxYear.Enabled = false;
TextBoxSemester.Enabled = false;
}
else
{
MessageBox.Show("Error");
}
conn.Close();