当从数据库读取和写入时,设备会以指数方式减慢,并且当该过程重复时,它会变得慢得多。有没有办法加快处理速度? 我正在编写C#Windows应用程序的程序 代码正常工作并没有问题,但问题只在于慢速可执行文件。 如下面的代码所示,我从第一个单元格中取出学生编号,然后在数据库中查找是否存在学生记录: 如果我们找到学生的记录,将指示向导更新学生数据 如果未找到学生记录,则会将新学生记录添加到学生表中 重新执行时,这是一个非常慢的代码:
prog1.Value = 0;
prog2.Value = 0;
prog1.Maximum = DGV1.RowCount;
string muoadNotSave = "";
prog2.Maximum = 7;
for (int i = 0; i < DGV1.RowCount; i += 5)
{
FlushMemory();//دالة تفريغ الذاكرة
if (prog1.Value < DGV1.RowCount - 2)
{
prog1.Value += 5;
}
else
{
prog1.Value += 1;
}
try
{
if (DGV1.Rows[i].Cells[16].Value != null)
{ string name = DGV1.Rows[i].Cells[15].Value.ToString();
int cell_no = DGV1.ColumnCount - 4;//عدد خلايا الصف
for (int o = 0; o <= 6; o++)
{
prog2.Value += 1;
int shoabah_No = 0;
int studenID =
int.Parse(DGV1.Rows[i].Cells[16].Value.ToString());
string ShoabahName =
DGV1.Rows[i].Cells[cell_no].Value.ToString();
OleDbConnection con77 = new
OleDbConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["acce"].ToString());
OleDbCommand com77 = new OleDbCommand();
com77.Connection = con77;
com77.CommandText = "SELECT * FROM Table_Shoab
where shoba_name ='" + ShoabahName + "'";
con77.Open();
OleDbDataReader r77 = com77.ExecuteReader();
while (r77.Read())
{
shoabah_No =
int.Parse(r77["shoba_id"].ToString());
}
con77.Close();
if (shoabah_No != 0)
{
OleDbConnection con6 = new
OleDbConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["acce"].ToString());
OleDbCommand com6 = new OleDbCommand();
com6.Connection = con6;
com6.CommandText = "insert into
link_stud_shobah (shoba_id,JLOS_NO) values
('" + shoabah_No + "','" + studenID + "')";
con6.Open();
com6.ExecuteNonQuery();
if (con6.State == ConnectionState.Open)
con6.Close();
}
else
{
muoadNotSave +=
DGV1.Rows[i].Cells[cell_no].Value.ToString()
+ " " + studenID + "\n\r";
}
cell_no += -2;
}
prog2.Value = 0;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
MessageBox.Show("اما ان يكون هناك مشكلة في الاتصال او ان الطالب "
+ " " + DGV1.Rows[i].Cells[23].Value + " " + " سبق تسجيلة ",
"تنبيه");
// MessageBox.Show("" + ex, "تنبيه");
}
finally
{
}
}
if (muoadNotSave != "")
{
MessageBox.Show("الشعب التي لم تحفظ "+muoadNotSave,
"تنبيه");
}
else
{
MessageBox.Show("تم حفظ كافة الشعب بنجاح ولله الحمد " +
muoadNotSave, "تنبيه");
}
答案 0 :(得分:0)
您正在创建,打开和关闭(嵌套)循环中的OleDbConnection
,这很昂贵。
尝试在外部循环之外执行以下操作:
OleDbConnection con77 = new OleDbConnection ..
OleDbCommand com77 = new OleDbCommand();
com77.Connection = con77;
con77.Open();
..
con77.Close();
OleDbConnection con6 = new OleDbConnection ..
OleDbCommand com6 = new OleDbCommand();
com6.Connection = con6;
con6.Open();
..
con6.Close();
此外,如果两个连接都相同,则只需创建一个。
不确定FlushMemory()
是做什么的,但这也可能很昂贵,在主循环后调用此函数可能会更好,或者根本不需要。