【发布时间】:2014-09-03 06:13:00
【问题描述】:
我正在尝试将大量数据从 CSV 文件导入 SQL Sever 数据库表。我可以逐行写,但这需要太长时间。在 oComm.Execute 期间,我下面的内容在“FROM [C:\Temp\tblOPTExportData.csv]”上失败。任何帮助将不胜感激。
On Error GoTo err_me
Dim locComm As New ADODB.Command
Dim locConnection As New ADODB.Connection
Dim locRst As New ADODB.Recordset
Dim ee As Boolean
Dim su As Boolean
Dim strSQLQuery As String
Dim shtDash As Worksheet
Dim shtData As Worksheet
Dim shtOP As Worksheet
With Application
ee = .EnableEvents
su = .ScreenUpdating
If ee Then .EnableEvents = False
If Not su Then .ScreenUpdating = True
End With
With ThisWorkbook
Set shtDash = .Sheets("Dashboard")
Set shtData = .Sheets("Data")
Set shtOP = .Sheets("OP")
End With
With locConnection
.CommandTimeout = 0
.ConnectionString = "Provider=SQLOLEDB;Server=sql-ewhcld-1000; Database=xxxxxxxxxxxxxx; User ID=tenant-xxxxxxxxxxxxxxx; Password=yeahidontthinkso; Trusted_Connection=True; Pooling=True; MultipleActiveResultSets=False"
.Open
End With
' ____________________________
' / \
' | IMS Factory Model Data |
' \____________________________/
'
'With statRng
' .Value = "Factory Model Phase Data // Importing"
' .Font.Color = 8421504
' .Characters(Start:=29, Length:=9).Font.Color = 10192433 'Blue
'End With
With shtOP
endRow = .Cells(.Rows.count, 2).End(xlUp).Row 'B (2)
End With
If endRow < 3 Then Err.Raise Number:=vbObjectError + 20002, Source:="exportData_Excel", Description:="No data found: 'OP' sheet, column 2 (B)."
If Not rangetoCSV("B3:K" & endRow, "tblOPTExportData", 201, , , "OP") Then Err.Raise Number:=vbObjectError + 30001, Description:="rangetoCSV, 'tblGates'"
strSQLQuery = "INSERT INTO optData (opsType, opsUID, opsDesc, opsProgram, opsFlight, opsProductAreaL1, opsAssignee, opsGenDate, opsECD, opsStatus) " & _
"SELECT Type, UID, Description, Program, Flight, L-1 IPT, Assignee, Generated, ECD, Status FROM [C:\Temp\tblOPTExportData.csv]"
With oComm
.ActiveConnection = locConnection
.CommandText = strSQLQuery
.Execute
End With
【问题讨论】:
-
如果您关心性能,为什么需要在 Excel 中执行此操作?你说的是多少行,多快才够快?
-
@NYCdotNet,数据似乎来自 Excel,导出到 csv 文件只是为了进行批量导入。
-
@"randomdownvoter" 为什么投反对票?反对票应附有解释,尤其是对于提出第一个问题的人。