|
楼主 |
发表于 2023-1-5 03:55
|
显示全部楼层
首先说谢谢回复, 我要的不是那个。
我的CSV格式数据很大,大概10万条一个文件,近100个CSV文件,如果用数组的话怕很慢。
我已经写了xls/xlsx格式的可以批量导入SQL数据库,但是那段代码只支持xls/xlsx格式的,如果转成xls/xlsx格式,行数不够,我只能用CSV格式批量导入到SQL。我的CSV文件格式都是标准的,标题都在第一行。我的诉求就是怎么修改我的代码,快速批量的导入CSV格式批量导入到SQL。看那个高手能修改一下我的ADO代码。代码如下:
Sub 批量导入xls文件到sql()
#If ProjectStatus = "DEV" Then
' needs reference for Microsoft ActiveX Data Objects
Dim cn As ADODB.Connection
' Dim fld As ADODB.Field
' Dim rs As ADODB.Recordset
' Set cn = New ADODB.Connection
' Set rs = New ADODB.Recordset
#Else ' assume PROD
' Const adCmdText As Long = 1
' Const adLockReadOnly As Long = 1
' Const adOpenForwardOnly As Long = 0
Dim cn As Object
' Dim fld As Object
' Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
' Set rs = CreateObject("ADODB.Recordset")
#End If
Const dizhi As String = "D:\数据\" '这个路径名最后一定要有一个反斜杠 "\"
Const geshiC As String = ".csv" '(如果是2007版,则后缀名请改为 *.xlsx)
Const geshiX As String = ".xlsx" '(如果是2007版,则后缀名请改为 *.xlsx)
Dim strSQL As String
Dim lngRecsAff As Long
Dim Headers As Boolean
Dim strConn As String
Dim path As String, fnTemp As String
Dim start As Double
start = Timer() '计算这个程序运行时间。
On Error GoTo test_Error
Dim Wb As Workbook
Dim ws As Worksheet
Dim fn, fp
'关闭屏幕刷新
Application.ScreenUpdating = False
fp = dizhi
fn = Dir(fp & "*" & geshiX) '取得第一个工作簿的文件名
'MsgBox "文件:" & fn
Dim wenjianming, wenjishuzu
wenjianming = ""
Do While fn <> ""
Headers = True
wenjishuzu = Split(fn) '文件名默认中间空格隔开
wenjianming = wenjishuzu(UBound(wenjishuzu)) '空格后面内容
wenjianming = LCase(Replace(wenjianming, geshiX, "")) '去掉格式后缀并小写,得到其中区别,这里是数据库表名
path = fp & fn
fnTemp = Replace(fn, geshiX, "")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";" & "Extended Properties=""Excel 8.0; IMEX=1;HDR=YES""" '这条语句支持xls/xlsx格式文件,不支持CSV格式
Debug.Print strConn
cn.Open strConn
strSQL = "Insert INTO [odbc;Driver={SQL Server};" & _
"Server=.;Database=数据库名;" & _
"UID=用户名;PWD=密码]." & wenjianming & " Select 字段一,字段二,字段三,字段四,字段五,字段六 FROM [" & fnTemp & "$] "
Debug.Print strSQL
cn.Execute strSQL, lngRecsAff
Debug.Print "Records affected: " & lngRecsAff
fn = Dir() '取得下一个工作簿的文件名
cn.Close
Loop '循环
Set cn = Nothing
'打开屏幕刷新
Application.ScreenUpdating = True
fenzhong = Int(Format(Timer - start, "0.00") / 60)
MsgBox "程序运行时间约是 " & fenzhong & " 分钟."
On Error GoTo 0
Exit Sub
test_Error:
MsgBox "strSQL=" & strSQL & Chr(10) & " Error " & Err.Number & " (" & Err.Description & ") in procedure test of VBA Document ThisWorkbook"
End Sub
|
|