在我的结算表单中,我有一个按钮,可以将datagridview数据插入两个访问数据库。 我使用此代码插入第一个数据库:
Private Sub inserttotblbill()
Dim billcon As OleDbConnection = New OleDbConnection(constr)
Dim billcmd As New OleDbCommand
For i = 0 To dgv.Rows.Count - 1
billcon.Open()
billcmd.Connection = billcon
billcmd.CommandText = ("insert into tblbill(inum,snum,idate,cname,iname,iprc,iqnt,ipaid,itotal,iuser,itype) " _
& " values('" _
& TextBox1.Text _
& "','" _
& TextBox6.Text _
& "','" _
& TextBox2.Text _
& "','" _
& TextBox3.Text _
& "','" _
& dgv.Rows(i).Cells(0).Value _
& "','" _
& dgv.Rows(i).Cells(1).Value _
& "','" _
& dgv.Rows(i).Cells(2).Value _
& "','" _
& TextBox4.Text _
& "','" _
& dgv.Rows(i).Cells(3).Value _
& "','" _
& username _
& "','" _
& Label2.Text _
& "')")
If Not ListBox1.Items.Contains(dgv.Rows(i).Cells(4).Value) Then
ListBox1.Items.Add(dgv.Rows(i).Cells(4).Value)
End If
billcmd.ExecuteNonQuery()
billcon.Close()
Next i
end sub
我使用此代码插入第二个数据库:
Private Sub inserttoreport()
Dim rptcon As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003")
Dim rptcmd As New OleDbCommand
For k = 0 To dgv.Rows.Count - 1
rptcon.Open()
rptcmd.Connection = rptcon
If dgv.Rows(k).Cells(4).Value = "101" Then
rptcmd.CommandText = ("insert into tab1(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13) " _
& " values('" _
& TextBox1.Text _
& "','" _
& TextBox6.Text _
& "','" _
& TextBox2.Text _
& "','" _
& TextBox3.Text _
& "','" _
& dgv.Rows(k).Cells(0).Value _
& "','" _
& dgv.Rows(k).Cells(1).Value _
& "','" _
& dgv.Rows(k).Cells(2).Value _
& "','" _
& TextBox4.Text _
& "','" _
& dgv.Rows(k).Cells(3).Value _
& "','" _
& TextBox5.Text _
& "','" _
& Label2.Text _
& "','" _
& username _
& "','" _
& xxxx _
& "')")
ElseIf dgv.Rows(k).Cells(4).Value = "102" Then
rptcmd.CommandText = ("insert into tab2(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13) " _
& " values('" _
& TextBox1.Text _
& "','" _
& TextBox6.Text _
& "','" _
& TextBox2.Text _
& "','" _
& TextBox3.Text _
& "','" _
& dgv.Rows(k).Cells(0).Value _
& "','" _
& dgv.Rows(k).Cells(1).Value _
& "','" _
& dgv.Rows(k).Cells(2).Value _
& "','" _
& TextBox4.Text _
& "','" _
& dgv.Rows(k).Cells(3).Value _
& "','" _
& TextBox5.Text _
& "','" _
& Label2.Text _
& "','" _
& username _
& "','" _
& xxxx _
& "')")
End If
rptcmd.ExecuteNonQuery()
rptcon.Close()
Next k
End Sub
但是当我按下按钮执行上述代码时,需要一段时间 我怎样才能让它更快?
答案 0 :(得分:5)
首先,将连接移出循环:
billcon.Open()
billcmd.Connection = billcon
For i = 0 To dgv.Rows.Count - 1
' ...
Next
billcon.Close()
答案 1 :(得分:0)
您可以使用Multi Thread来加速代码。 Task Class
这也是vb的版本。尝试使用背景线程进行高度重量处理。