在我的ASP代码中,当使用asp引擎作为服务器端脚本运行时,我有以下没有问题。但是,当我在VBS文件中运行与VB脚本相同的连接时,它从不连接到数据库?我有Windows 2008和2008 R2 MSSQL。有什么想法吗?
establish connection
function DatabaseConnection()
' establish connection if not connected already
if not IsObject(objGlobalConn) then
if Len(Application("WebConnectionString")) = 0 then
Set oShell = CreateObject("WScript.Shell")
Application.Lock
Application("WebConnectionString") = oShell.RegRead("HKLM\SOFTWARE\TB\ConnectionString3")
Application.Unlock
end if
set objGlobalConn = CreateObject("ADODB.Connection")
objGlobalConn.ConnectionTimeout = 0
objGlobalConn.CommandTimeOut = 0
objGlobalConn.CursorLocation = 3 ' adUseClient
objGlobalConn.Open Application("WebConnectionString")
end if
' return connection object
set DatabaseConnection = objGlobalConn
end function
我的VBScript文件:
' get the connection string
Set oShell = CreateObject("WScript.Shell")
sConnectionString = oShell.RegRead("HKLM\SOFTWARE\TB\ConnectionString3")
Set oShell = Nothing
答案 0 :(得分:0)
Application对象仅在ASP下运行VBScript时存在。如果通过WScript.exe或CScript.exe在Windows脚本宿主(WSH)下运行.vbs文件,则Application对象不可用。 (我猜这里有一个On Error Resume Next
语句可以抑制WSH正在引发的错误消息。)
根据您是否确实需要在Application对象中存储连接字符串,可以想到两个解决方案。假设在Application("WebConnectionString")
函数之外未使用DatabaseConnection
,则可以删除对Application
的引用。然后该函数可以在ASP和WSH下运行:
function DatabaseConnection()
Dim objGlobalConn, oShell, connectionString
' establish connection if not connected already
if not IsObject(objGlobalConn) then
Set oShell = CreateObject("WScript.Shell")
connectionString = oShell.RegRead("HKLM\SOFTWARE\TB\ConnectionString3")
Set oShell = Nothing
set objGlobalConn = CreateObject("ADODB.Connection")
objGlobalConn.ConnectionTimeout = 0
objGlobalConn.CommandTimeOut = 0
objGlobalConn.CursorLocation = 3 ' adUseClient
objGlobalConn.Open connectionString
end if
' return connection object
set DatabaseConnection = objGlobalConn
end function
但是,如果在Application("WebConnectionString")
函数之外使用DatabaseConnection
,则需要更多代码才能使函数在ASP和WSH下工作。引用Application
对象或任何其他与ASP相关的对象的代码的其他部分需要同样受到IsRunningUnderASP
调用的保护:
function DatabaseConnection()
Dim objGlobalConn, oShell, connectionString
' establish connection if not connected already
if not IsObject(objGlobalConn) then
Set oShell = CreateObject("WScript.Shell")
connectionString = oShell.RegRead("HKLM\SOFTWARE\TB\ConnectionString3")
Set oShell = Nothing
If IsRunningUnderASP() And (Len(Application("WebConnectionString")) = 0) then
Application.Lock
Application("WebConnectionString") = connectionString
Application.Unlock
End If
set objGlobalConn = CreateObject("ADODB.Connection")
objGlobalConn.ConnectionTimeout = 0
objGlobalConn.CommandTimeOut = 0
objGlobalConn.CursorLocation = 3 ' adUseClient
objGlobalConn.Open connectionString
end if
' return connection object
set DatabaseConnection = objGlobalConn
end function
Function IsRunningUnderASP
IsRunningUnderASP = _
IsObject(Application) And _
IsObject(Request) And _
IsObject(Response)
End Function