使用ado和vbscript从csv更新数据库而不使用记录集循环?

时间:2013-06-12 01:48:41

标签: csv vbscript ms-access-2007 ado

我想使用Vb Script& amp ;;将数据从csv文件上传到Access数据库。 ADO所以我不必打开Access或Excel。

到目前为止,我有一个工作脚本,但是有没有更好的方法可以在一个批次中上传数据而无需创建记录集并循环遍历每条记录?

我创建了一个示例,其中我有2个原始数据文件(csv),文件People.csv包含字段'PERSON'和'COMPANY',另一个文件包含'COMPANY'和'STATUS'。要更新的数据库有一个表'tblPeople',其中包含Fields'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

1 个答案:

答案 0 :(得分:2)

使用“INSERT / SELECT INTO IN'外部数据库'”。对于您的特定任务(文本 - > mdb, 您的查询)语句看起来像

Create new table:
SELECT T1.PERSON AS PERSON, T2.STATUS AS STATUS INTO [tblPeople] IN "P:\athto\your.mdb.mdb" FROM [People#csv] T1 INNER JOIN [Company#csv] T2 ON T1.COMPANY = T2.COMPANY

Append to existing table:
INSERT INTO [tblPeople] IN "P:\athto\your.mdb.mdb" SELECT T1.PERSON AS PERSON, T2.STATUS AS STATUS FROM [People#csv] T1 INNER JOIN [Company#csv] T2 ON T1.COMPANY = T2.COMPANY