批量插入数据(dataTable至SQL SERVER)
一般我们要将数据插入数据库时,一般使用insert into 语句,但是如果当数据量很大时,使用SqlBulkCopy进行批量导入有一定的性能优势。
SqlBulkCopy 类
使您可以用其他源的数据有效批量加载 SQL Server 表。
命名空间: System.Data.SqlClient
程序集: System.Data(在 System.Data.dll 中)
语法
Public NotInheritable Class SqlBulkCopy Implements IDisposable
备注
Microsoft SQL Server 提供一个称为 bcp 的流行的命令提示符实用工具,用于将数据从一个表移动到另一个表(表既可以在同一个服务器上,也可以在不同服务器上)。 SqlBulkCopy 类允许编写提供类似功能的托管代码解决方案。 还有其他将数据加载到 SQL Server 表的方法(例如 INSERT 语句),但相比之下 SqlBulkCopy 提供明显的性能优势。
使用 SqlBulkCopy 类只能向 SQL Server 表写入数据。 但是,数据源不限于 SQL Server;可以使用任何数据源,只要数据可加载到 DataTable 实例或可使用 IDataReader 实例读取数据。
代码示例:
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString As String = GetConnectionString()
'打开数据连接
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString)
sourceConnection.Open()
' 执行行数
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
sourceConnection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' 获取源数据
Dim commandSourceData As SqlCommand = New SqlCommand( _
"SELECT ProductID, Name, ProductNumber " & _
"FROM Production.Product;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
' Open the destination connection. In the real world you would
' not use SqlBulkCopy to move data from one table to the other
' in the same database. This is for demonstration purposes only.
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString)
destinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
bulkCopy.DestinationTableName = _
"dbo.BulkCopyDemoMatchingColumns"
Try
' Write from the source to the destination.
bulkCopy.WriteToServer(reader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - countStart)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the sourceConnection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);" & _
"Integrated Security=true;" & _
"Initial Catalog=AdventureWorks;"
End Function
End Module
如果大家觉得这些示例还是麻烦的话,可以花9.9去购买一个pgzzCnn.dll,该库使用炒鸡简单,包含了几乎所有的数据库操作,支持SqlClient、OleDb和Odbc方式,支持连接SQLSERVER、ACCESS、Oracle以及MYSQL,支持SELECT、UPDATE、INSERT操作,特别是支持批量写入(datatable到数据库)和数据库事务处理。
使用示例:
公共模块声明:
Private strConn As String = "Data Source=服务器实例;Initial Catalog=数据库;User ID=sa;Password=密码"
Public Csql As pgzz.sqlserver ’ 不同数据源可声明为对应的方式oledb/odbc
获取表:
Dim strSQL As String = "select * from 表1 where 查询条件"
Dim tt As DataTable = Csql.GetTable(strSQL)
更新或插入:
Dim strSQL As String = "update 表 set 字段=’值’ where 条件"
Dim exCount As integer = Csql. DoSql (strSQL) ‘dosql返回受影响的行数
批量插入(sqlserver支持,其它不支持):
dim sw as long = Csql. DoSql(newTable,tableName) ‘这里返回的是执行的时间(ms),如返回0则代表出错了。
'tableName为目标表(sqlserver中的表名)。
‘newTable为待更新的数据源,可以是任意数据源,但需与tableName结构一致。
数据库事务:
Dim strSQL As String
Dim strL As New List(Of String)
strSQL = " insert into 表1(字段1,字段2……) values(值1,……)"
strL.Add(strSQL)
strSQL = " update表2 set 字段1=值 where 条件"
strL.Add(strSQL)
If Csql.DoSql(strL) Then
‘执行成功!
Else
‘执行失败!
End If
是不是炒鸡简单呢?
9块9,买不了吃亏,买不了上当,pgzzCnn,你值得拥有(需要源码可以跟店主私聊)。
闲鱼链接:
https://market.m.taobao.com/app/idleFish-F2e/widle-taobao-rax/page-detail?wh_weex=true&wx_navbar_transparent=true&id=586152596728&ut_sk=1.WfFNPGwSx70DACo2hZcTFezZ_21407387_1548072402925.Copy.detail.586152596728.320966645&forceFlush=1
或在闲鱼搜索
“数据库使用程序集”