Croote
Croote

Reputation: 1424

dbBind function error when trying to set up parameterized query on SQL Server

I am trying to do some parameterized queries using the DBI package dbSendQuery, dbBind and dbFetch workflow.

I am able to use the dbSendQuery using ? as a placeholder for a variable. however, when I run dbBind I get the following error:

Error in (function (classes, fdef, mtable)  :
unable to find an inherited method for function 'dbBind' for signature '"Microsoft SQL Server"'

The whole of my code looks like this:

library(odbc)
library(DBI)
test_connection <- DBI::dbConnect(odbc::odbc(),
                                  Driver = "SQL Server",
                                  Server = "MyServer",
                                  Database = "MyDataBase")
test_query <- dbSendQuery(test_connection,
                          "SELECT TOP 2 col1, col2 FROM MyTable WHERE col2 = ?")
dbBind(test_connection,
       list('value'))

Error in (function (classes, fdef, mtable)  :
            unable to find an inherited method for function 'dbBind' for signature '"Microsoft SQL Server"'

Can anyone explain to me the reason for this error?

If I hard code value in the dbSendQuery statement and use dbFetch the query does work.

Upvotes: 1

Views: 428

Answers (1)

Willem
Willem

Reputation: 1124

In dbBind you should use the query object instead of the connection object. In your example:

dbBind(test_query, list('value'))

Upvotes: 1

Related Questions