问题
If I want to connect R to a database, do I still need to install driver for R user?
I had done successful connection with server but unable to read/write/fetch the tables.
library(odbc)
con <- dbConnect(odbc::odbc(),
.connection_string = 'driver={SQL Server};server=DW01;database=AF_DW;trusted_connection=true')
Now I can see AF_DW in RStudio connections.
dbListFields(con, "Visits")
I can see all the variables in the table "Visits"
data <- dbReadTable(con, "Visits")
Got an Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Visits'. [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. 'SELECT * FROM "Visits")
data3 <- dbGetQuery(con, "SELECT * FROM Visits")
Got same error
data4 <- dbSendQuery(con, "SELECT * FROM Visits")
Got same error
con_in_R <- dbFetch(dbSendQuery(con,"SELECT * FROM Visits"))
Error in (function (cond) : error in evaluating the argument 'res' in selecting a method for function 'dbFetch': nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Visits'. [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. 'SELECT * FROM Visits'
Appreciate your help. Thank you.
回答1:
According to you image, Visits
is not stored in the default dbo
schema as all your queries assume but under the eCW
schema.
Like most RDBMS's, SQL Server follows the three part name convention for objects (tables, stored procedures, functions): [database].[schema].[object]
where database is not necessary for a database specific connection and schema not necessary for dbo
default.
Therefore, you need to reference schema and table name in your attempted queries.
s <- Id(schema = "eCW", table = "Visits")
# READ FROM NON-DEFAULT SCHEMA TABLE
data3 <- dbReadTable(con, s)
data3 <- dbGetQuery(con, "SELECT * FROM [eCW].[Visits]")
# WRITE TO NON-DEFAULT SCHEMA TABLE
dbWriteTable(conn, s, mydataframe)
dbWriteTable(con, SQL("eCW.Visits"), mydataframe)
来源:https://stackoverflow.com/questions/65014679/save-or-read-data-from-sql-server-in-to-r-using-odbc-package