我想使用 Vb Script & ADO 将数据从 csv 文件上传到 Access 数据库,因此我不必打开 Access 或 Excel。
到目前为止,我在下面有一个工作脚本,但是有没有更好的方法可以批量上传数据而无需创建记录集并循环遍历每条记录?
我创建了一个示例,其中我有 2 个原始数据文件 (csv),文件 People.csv 包含字段“PERSON”和“COMPANY”,另一个文件包含“COMPANY”和“STATUS”。要更新的数据库有一个表 'tblPeople',其中包含字段 'PERSON' 和 'STATUS'。
Const ST_FILES = "C:\test\Files\"
Const ST_DB = "C:\test\db\mydb.accdb"
'Connection to Raw Files
Dim stCS: stCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ST_FILES & _
";Extended Properties=""text;HDR=YES;FMT=Delimited(,)"";"
Dim objCnFiles: set objCnFiles = CreateObject("ADODB.Connection"):objCnFiles.open stCS
'Connection to DB
stCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ST_DB
Dim objCnDb: set objCnDb = CreateObject("ADODB.Connection"):objCnDb.Open stCS
'Recordset of Raw Files
Dim objRS: set objRS = CreateObject("ADODB.RecordSet")
Dim stSQL: stSQL = "SELECT T1.PERSON, T2.STATUS " & _
"FROM People#csv T1 " & _
"INNER JOIN Company#csv T2 "& _
"ON T1.COMPANY = T2.COMPANY"
objRS.open stSQL, objCnFiles
'The part Below is the part I want to improve:
'Loops through the recordset inserting record into db line by line.
objRS.MoveFirst
Do until objRS.EOF
stSQL = "INSERT INTO tblPeople (PERSON, STATUS) " & _
"VALUES('" & objRS.Fields("PERSON") & "','" & _
objRS.Fields("STATUS") & "')"
objCnDb.Execute stSQL
objRS.MoveNext
Loop
objRS.close
objCnFiles.close
objCnDb.close
WScript.echo "Done"
WScript.Quit
编辑:下面的解决方案使用 Ekkehard.Horner 提供的解决方案
Const ST_FILES = "C:\test\Files\"
Const ST_DB = "C:\test\db\mydb.accdb"
'Connection to Raw Files
Dim stCS: stCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ST_FILES & _
";Extended Properties=""text;HDR=YES;FMT=Delimited(,)"";"
Dim objCnFiles: set objCnFiles = CreateObject("ADODB.Connection"):objCnFiles.open stCS
Dim stSQL: stSQL = "INSERT INTO [tblPeople] IN '" & ST_DB & "'" &_
"SELECT T1.PERSON, T2.STATUS " & _
"FROM People#csv T1 " & _
"INNER JOIN Company#csv T2 "& _
"ON T1.COMPANY = T2.COMPANY"
objCnFiles.Execute stSQL
objCnFiles.close
WScript.echo "Done"
WScript.Quit