简体   繁体   English

使用.bat通过ODBC连接到SQL

[英]Connect to SQL via ODBC using a .bat

I am currently performing a SQL query using Oracle SQL Developer and pasting in a standard query (same SELECT every time), then exporting to a csv file. 我目前正在使用Oracle SQL Developer执行SQL查询,并粘贴到标准查询中(每次都选择SELECT),然后导出到csv文件。 I would like to execute the query via a batch file and place the output in a specified folder. 我想通过批处理文件执行查询,并将输出放置在指定的文件夹中。 I already use many batch files on this machine and would like to make this query part of a routine. 我已经在这台计算机上使用了许多批处理文件,并且希望将此查询作为例程的一部分。

My machine has an existing ODBC connection to "WHPROD", but I do not know how to use it. 我的机器已经与“ WHPROD”建立了ODBC连接,但是我不知道如何使用它。 Is there a way to connect to WHPROD from a batch file? 有没有一种方法可以从批处理文件连接到WHPROD?

This is hardly possible in batch script directly without going overcomplicated 在不过度复杂的情况下,直接在批处理脚本中几乎不可能做到这一点

However it is simple to do it with VBscript, and since you can call your VBscript from a batch script, the result will be exactly what you want. 但是,使用VBscript进行操作很简单,并且由于可以从批处理脚本调用VBscript,因此结果将完全符合您的要求。

Here's an example of how to connect to Oracle and retrieve the results of a SELECT from VBS : ( source ) 这是一个如何连接到Oracle并从VBS检索SELECT结果的示例:( source

Dim strCon

strCon = “Driver={Microsoft ODBC for Oracle}; ” & _
         “CONNECTSTRING=(DESCRIPTION=” & _
         “(ADDRESS=(PROTOCOL=TCP)” & _
         “(HOST=Server_Name)(PORT=1521))” & _
         “(CONNECT_DATA=(SERVICE_NAME=DB_Name))); uid=system;pwd=system;”

Dim oCon: Set oCon = WScript.CreateObject(“ADODB.Connection”)
Dim oRs:  Set oRs  = WScript.CreateObject(“ADODB.Recordset”)
oCon.Open strCon

Set oRs = oCon.Execute(“SELECT name from v$database”)

While Not oRs.EOF
   WScript.Echo oRs.Fields(0).Value
   oRs.MoveNext
Wend
oCon.Close

Set oRs = Nothing
Set oCon = Nothing

And here's how to call your VBS from the batch script : 这是从批处理脚本调用VBS的方法:

@echo off

start "C:\\yourbatchfolder\\yourscript.vbs"

I wrote an in-depth batch script once that builds a MSSQL database. 一旦构建了MSSQL数据库,我就编写了一个深入的批处理脚本 There are lots of great hints in that script that may help you get going. 该脚本中有很多很棒的提示,可能会帮助您继续前进。

The script is not specifically using ODBC but I do believe SQLCMD args can be changed to use a ODBC defined connection? 该脚本不是专门使用ODBC,但是我相信可以将SQLCMD args更改为使用ODBC定义的连接吗? That may work for you; 那可能对你有用; and not just on MSSQL server. 而不只是在MSSQL服务器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM