vbscript:如何用ado查询csv并返回csv

时间:2016-04-06 15:30:39

标签: vbscript ado

我正在尝试使这个脚本工作(有一些vba知识,不知道vbs的差异。我想要适应的解决方案在这里: VB Script to dump an SQL Server table to CSVhttps://msdn.microsoft.com/en-us/library/ms974559.aspx

应该读取csv文件,对其运行ACE SQL查询并将结果返回给另一个CSV

它只生成一个空的Output.csv文件,并被锁定以进行编辑。你能帮我解决一下:

On Error Resume Next 

Const adOpenStatic = 3 
Const adLockOptimistic = 3 
Const adCmdText = &H0001 

Set cn = CreateObject("ADODB.Connection") 
Set rs = CreateObject("ADODB.Recordset") 

strPathtoTextFile = "C:\Databases\" 

cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
          "Data Source=" & strPathtoTextFile & ";" & _ 
          "Extended Properties=""text;HDR=YES;FMT=Delimited""" 

rs.Open "SELECT * FROM PhoneList.csv", _ 
          objConnection, adOpenStatic, adLockOptimistic, adCmdText 


Set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile("c:\Databases\output.csv",2,TRUE)
line=""
For Each tmp In objRecordset.Fields
   line=line & tmp.Name & ","
Next

ts.WriteLine Left(line,Len(line)-1)
While Not rs.EOF
 line=""
 For Each tmp In rs.Fields
  If IsNull(tmp.Value) Then
   line=line & """" & Replace(tmp.Value,"""","""""") & ""","
  Else
   line=line & """" & tmp.Value & ""","
  End If
 Next
 ts.WriteLine Left(line,Len(line)-1)
 rs.MoveNext
Wend

Set rs = Nothing
ts.close
rs.close
fso.close

cn.Close

我理解一些VBA,但我无法在这个VBS中找到出路。你能帮我看看我做错了什么吗?

其次......是否可以制作相对于脚本本身的所有数据路径,以便可以分发解决方案?我知道如何在vba中执行此操作,但不知道是否可以使用vbscript?

我确信这样的模板对所有社区都非常有帮助。如果我的问题不合理,我会谦卑地接受批评。

1 个答案:

答案 0 :(得分:0)

我在这里添加了代码的工作版本。您应该有助于删除“On Error Resume Next”并尝试修复突出显示的错误。没有多少,他们并不难解决,但练习应该提供信息。这是代码的工作版本:

On Error Resume Next 

Const adOpenStatic = 3 
Const adLockOptimistic = 3 
Const adCmdText = &H0001 

Set cn = CreateObject("ADODB.Connection") 
Set rs = CreateObject("ADODB.Recordset") 

strPathtoTextFile = "C:\Databases\"

cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
          "Data Source=" & strPathtoTextFile & ";" & _ 
          "Extended Properties=""text;HDR=YES;FMT=Delimited""" 

rs.Open "SELECT * FROM PhoneList.csv", _ 
          cn, adOpenStatic, adLockOptimistic, adCmdText 


Set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile(strPathtoTextFile & "output.csv",2,TRUE)
line=""
For Each tmp In rs.Fields
   line=line & tmp.Name & ","
Next
ts.WriteLine Left(line,Len(line)-1)

While Not rs.EOF
 line=""
 For Each tmp In rs.Fields
  If IsNull(tmp.Value) Then
   line=line & """" & Replace(tmp.Value,"""","""""") & ""","
  Else
   line=line & """" & tmp.Value & ""","
  End If
 Next
 ts.WriteLine Left(line,Len(line)-1)
 rs.MoveNext
Wend

rs.close
Set rs = Nothing
ts.close
cn.Close