Я работал VBScript ADO, который должен принять параметры и включить те параметры в Строку запроса, которая передается база данных. Я продолжаю получать ошибки, когда Объект Официального набора документов пытается открыться. Если я передаю запрос без параметров, recordset открывается, и я могу работать с данными. Когда я запускаю скрипт через отладчик, объект команды не показывает значение для объекта параметра. Мне кажется, что я пропускаю что-то, что связывает Объект команды и Объект параметра, но я не знаю что. Вот является немного Кодом VBScript:
...
'Open Text file to collect SQL query string'
Set fso = CreateObject("Scripting.FileSystemObject")
fileName = "C:\SQLFUN\Limits_ADO.sql"
Set tso = fso.OpenTextFile(fileName, FORREADING)
SQL = tso.ReadAll
'Create ADO instance'
connString = "DRIVER={SQL Server};SERVER=myserver;UID=MyName;PWD=notapassword; Database=favoriteDB"
Set connection = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
connection.Open connString
cmd.ActiveConnection = connection
cmd.CommandText = SQL
cmd.CommandType = adCmdText
Set paramTotals = cmd.CreateParameter
With paramTotals
.value = "tot%"
.Name = "Param1"
End With
'The error occurs on the next line'
Set recordset = cmd.Execute
If recordset.EOF then
WScript.Echo "No Data Returned"
Else
Do Until recordset.EOF
WScript.Echo recordset.Fields.Item(0) ' & vbTab & recordset.Fields.Item(1)
recordset.MoveNext
Loop
End If
Строка SQL, которую я использую, является довольно стандартной кроме, я хочу передать параметр ей. Это - что-то вроде этого:
SELECT column1
FROM table1
WHERE column1 IS LIKE ?
Я понимаю, что ADO должен заменить"?" со значением параметра я присваиваюсь в сценарии. Проблема, которую я вижу, состоит в том, что Объект параметра показывает правильное значение, но поле параметра объекта команды является пустым согласно моему отладчику.
Мне так и не удалось CreateParameter
сделать то, что я хотел. Правильная параметризация - необходимость избежать внедрения SQL, но CreateParameter
- это полный PITA. К счастью, есть альтернатива: Command.Execute
принимает параметры напрямую.
dim cmd, rs, rows_affected
set cmd = Server.createObject("adodb.command")
cmd.commandText = "select from Foo where id=?"
set cmd.activeConnection = someConnection
set rs = cmd.execute(rows_affected, Array(42))
Гораздо приятнее, когда он заключен в правильную абстракцию. Я написал свою собственную оболочку класса базы данных ADODB.Connection
, чтобы мне не пришлось делать все это вручную. Он немного зависит от других пользовательских классов, но суть должна быть очевидна:
class DatabaseClass
' A database abstraction class with a more convenient interface than
' ADODB.Connection. Provides several simple methods to safely query a
' database without the risk of SQL injection or the half-dozen lines of
' boilerplate otherwise necessary to avoid it.
'
' Example:
'
' dim db, record, record_set, rows_affected
' set db = Database("/path/to/db")
' set record = db.get_record("select * from T where id=?;", Array(42))
' set record_set = db.get_records("select * from T;", empty)
' rows_affected = db.execute("delete from T where foo=? and bar=?",
' Array("foo; select from T where bar=", true))
private connection_
' An ADODB connection object. Should never be null.
private sub CLASS_TERMINATE
connection_.close
end sub
public function init (path)
' Initializes a new database with an ADODB connection to the database at
' the specified path. Path must be a relative server path to an Access
' database. Returns me.
set connection_ = Server.createObject ("adodb.connection")
connection_.provider = "Microsoft.Jet.OLEDB.4.0"
connection_.open Server.mapPath(path)
set init = me
end function
public function get_record (query, args)
' Fetches the first record returned from the supplied query wrapped in a
' HeavyRecord, or nothing if there are no results.
dim data: set data = native_recordset(query, args)
if data.eof then
set get_record = nothing
else
set get_record = (new HeavyRecordClass).init(data)
end if
end function
public function get_records (query, args)
' Fetches all records returned from the supplied query wrapped in a
' RecordSet (different from the ADODB recordset; implemented below).
set get_records = (new RecordSetClass).init(native_recordset(query, args))
end function
public function execute (query, args)
' Executes the supplied query and returns the number of rows affected.
dim rows_affected
build_command(query).execute rows_affected, args
execute = rows_affected
end function
private function build_command (query)
' Helper method to build an ADODB command from the supplied query.
set build_command = Server.createObject("adodb.command")
build_command.commandText = query
set build_command.activeConnection = connection_
end function
private function native_recordset (query, args)
' Helper method that takes a query string and array of arguments, queries
' the ADODB connection, and returns an ADODB recordset containing the
' result.
set native_recordset = build_command(query).execute( , args) ' Omits out-parameter for number of rows
end function
end class