I am doing a college attendance project with Winforms, MySQL, and C#.
In that I want to update “Total Absent” and “Total Present” in one table. So I wrote code for that:
int p = 0;
int a = 0;
string sno = "";
MySqlDataReader Reader;
command.CommandText = "select * from attendance_monthly_rpt";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
p = 0;
a = 0;
sno = Reader[1].ToString();
for (int k = 3; k <= 33; k++)
{
if ((Reader[k].ToString() == "P") || (Reader[k].ToString() =="OD"))
{
p += 1;
}
else if (Reader[k].ToString() == "Ab")
{
a += 1;
}
}
}
connection.Close();
Now I get “sno”, “a”, “p” values for that. But I want to update this record in the MySQL table. So I added an UPDATE statement:
while (Reader.Read())
{
p = 0;
a = 0;
sno = Reader[1].ToString();
for (int k = 3; k <= 33; k++)
{
if ((Reader[k].ToString() == "P") || (Reader[k].ToString() =="OD"))
{
p += 1;
}
else if (Reader[k].ToString() == "Ab")
{
a += 1;
}
}
command.CommandText = "update attendance_monthly_rpt set tot_persent = " +
p + ", tot_absent = " + a + " where student_no = '" +
sno + "'";
connection.Open(); // the connection is already open
command.ExecuteNonQuery();
connection.Close();
}
connection.Close()
This throws the error “The connection is already open”. If I place the update statement after the loop, I get the last record only.
Please help me to update my “Tot absent”, “Tot present” for each “Student”.
Look at your code after you’ve removed most of what’s not related to opening or closing the connection:
It’s easy to see now why the connection is already open during the first run of the
whileloop.Apropos: I would suggest that you not
.Open()and.Close()the connection for every single command. (Connections should indeed not be kept open any longer than is necessary, but you’re probably exaggerating it a little there. 🙂 Instead, just open the connection once before you start your updates, and close it after thewhileloop. And, like CodeBuzz suggested already, put theconnection.Close()in afinallyblock to make sure the connection is closed even if something goes wrong.P.S.: Don’t forget to
.Dispose()all objects that areIDisposable(ie. the data reader and connection objects), e.g. via ausingblock.