将许多记录插入 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
将使用 SqlBulkCopy 类的 WriteToServer 方法将此 DataTable 插入到数据库中。
以下代码将提供的 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