我有50000条记录要显示在datagridview上然后我想将它保存到数据库,但插入SQL Server时速度很慢。
我的代码:
For x As Integer = 0 To Me.DataGridView1.Rows.Count - 1
With DataGridView1
Insert into tbl1 values("&.Rows(x).Cells(0).Value&", ......)
End With
Next
你有解决方案吗?
答案 0 :(得分:1)
将许多记录插入SQL Server表的快速方法是使用 SqlBulkCopy 类。
首先,您需要一个将DataGridView的内容复制到DataTable中的函数。
Private Function GetDataTable() As DataTable
Dim DataTable1 As New DataTable
Dim i1, i2, RowsCount1 As Integer
For i1 = 0 To DataGridView1.Columns.Count - 1
DataTable1.Columns.Add(DataGridView1.Columns(i1).Name, DataGridView1.Columns(i1).ValueType)
Next
If DataGridView1.AllowUserToAddRows = True Then
RowsCount1 = DataGridView1.Rows.Count - 1
Else
RowsCount1 = DataGridView1.Rows.Count
End If
For i1 = 0 To RowsCount1 - 1
DataTable1.Rows.Add(DataTable1.NewRow)
For i2 = 0 To DataGridView1.Columns.Count - 1
DataTable1.Rows(i1).Item(i2) = DataGridView1.Rows(i1).Cells(i2).Value
Next
Next
Return DataTable1
End Function
此DataTable将使用SqlBulkCopy类的WriteToServer方法插入到数据库中。
以下代码将提供的DataTable插入数据库。
Private Sub SaveToDatabase(ByVal DataTable1 As DataTable)
Dim ConnectionStr1 As String = "Server=ServerAddress;Database=DataBaseName;User Id=Username;Password=Password;"
Dim SqlBulkCopy1 As New SqlClient.SqlBulkCopy(ConnectionStr1)
SqlBulkCopy1.DestinationTableName = "TableName"
SqlBulkCopy1.ColumnMappings.Add("SourceColumn1", "DestinationColumn1")
SqlBulkCopy1.ColumnMappings.Add("SourceColumn2", "DestinationColumn2")
SqlBulkCopy1.ColumnMappings.Add("SourceColumn3", "DestinationColumn3")
'
'
SqlBulkCopy1.WriteToServer(DataTable1)
SqlBulkCopy1.Close()
End Sub