ADODB Command failing Execute with parameterised SQL query

﹥>﹥吖頭↗ 提交于 2019-12-31 03:36:09

问题


I have the following JScript code:

var conn = new ActiveXObject ("ADODB.Connection");
conn.Open("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=blah_blah_blah;User=foo;Password=bar;");
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;

var strSQL = "SELECT id FROM tbl_info WHERE title LIKE :search ORDER BY id";
var search = "test";

try{
    cmd.CommandText = strSQL;
    var param = cmd.CreateParameter(':search', 200, 1, 100, search);
    cmd.Parameters.Append(param);
    var rs = cmd.Execute();
    }
catch (ex) {
    Application.Alert("Error retrieving id information from database.");
}

I've verified (by printing them) that the Connection object is set to be the Command's ActiveConnection, the parameter object has the correct value and the Command object has the correct SQL query as its CommandText. I also inserted an alert statement after each line in the try block to see where the error was occuring - it's fine after cmd.Parameters.Append but the exception gets thrown upon running the Execute statement.

I've tried displaying the actual exception but it's just a generic 'Object error' message.

The query executes fine and returns the correct result set when I just execute the SQL query (without the parameter) straight through the Connection object, but seems to fail when I use a parameterised query with the Command object.

As far as I can see all settings and properties of the Command and Connection objects are correct but for whatever reason it's throwing an exception.

Any help with this would be much appreciated.


回答1:


With ODBC and ADO, generally speaking, a question mark ? is used as the placeholder for parameters. Parameters are bound in the order they are appended to the Parameters collection to the placeholders in the command. In your example, replace strSQL with:

var strSQL = "SELECT id FROM tbl_info WHERE title LIKE ? ORDER BY id";

You can still name the parameter that you create, but the only purpose it would serve is to be able to reference it by name later (e.g., with cmd.Parameters.Item(":search")).



来源:https://stackoverflow.com/questions/13064865/adodb-command-failing-execute-with-parameterised-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!