Hi guys, I am confused with the commit statement in MySql. I encountered an error in my program due to lock statement. However, one of my statement was successfully executed even if I have a rollback statement - the INSERT statement successfully executed.
HERE’s the original code that pertains to my confusion of commit and lock table statements.
try
{
cnDBConnection.Open();
cmStudent.Connection = cnDBConnection;
cmStudent.CommandText = "START TRANSACTION";
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "LOCK TABLES ids READ, ids AS ID WRITE";
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "SELECT id FROM ids";
rdID = cmStudent.ExecuteReader();
rdSID.Read();
strID = double.Parse(rdID["id"].ToString()).ToString("00000000");
rdID.Close();
cmStudent.CommandText = "LOCK TABLES studentreg WRITE";
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "INSERT INTO reg VALUES(@studentid, @lastname, @firstname," +
"@middlename, @citizenship, @prevschool, @prevcourse, @currcourse," +
"@gender)";
cmStudent.Parameters.AddWithValue("@studentid", strStudentID);
cmStudent.Parameters.AddWithValue("@lastname", txtLastName.Text.ToUpper());
cmStudent.Parameters.AddWithValue("@firstname", txtFirstName.Text.ToUpper());
cmStudent.Parameters.AddWithValue("@middlename", txtMiddleName.Text.ToUpper());
cmStudent.Parameters.AddWithValue("@citizenship", strCitizenship);
cmStudent.Parameters.AddWithValue("@prevschool", txtPreviousSchool.Text.ToUpper());
cmStudent.Parameters.AddWithValue("@prevcourse", string.Empty);
cmStudent.Parameters.AddWithValue("@currcourse", txtCourse.Text.ToUpper());
cmStudent.Parameters.AddWithValue("@gender", cboGender.Text);
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "UPDATE ids AS ID SET studentid=studentid+1";
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "COMMIT";
cmStudent.ExecuteNonQuery();
cmStudent.CommandText = "UNLOCK TABLES";
cmStudent.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message + "<br />" + ex.Source + "<br />" + ex.ToString());
cmStudent.CommandText = "ROLLBACK";
cmStudent.ExecuteNonQuery();
}
finally
{
cmNewStudent.Connection.Close();
cnDBConnection.Close();
}
With the given code above, there will be an error exist specifically on LOCK statement. Again my concern is the “INSERT STATEMENT” executed successfully.