[英]ODBC/DBI in R will not write to a table with a non-default schema in R
When trying to write to a table with a non-default schema, dbWriteTable
in the package DBI, writes to default.non-default.tablename
rather than writing to non-default.tablename
. 尝试写入具有非默认架构的表时,DBI包中的
dbWriteTable
写入default.non-default.tablename
而不是写入non-default.tablename
。 I know that non-default.tablename
exists because it's showing up in my SSMS database. 我知道
non-default.tablename
存在,因为它出现在我的SSMS数据库中。
Create this table in SQL Server with a non-default schema 'guest'. 使用非默认架构“guest”在SQL Server中创建此表。 I am placing it in a database called 'SAM':
我将它放在一个名为'SAM'的数据库中:
CREATE TABLE guest.MikeTestTable(
[a] [float] NULL,
[b] [float] NULL,
[c] [varchar](255) NULL)
#Create a df to insert into guest.MikeTestTable
df <- data.frame(a = c(10, 20, 30),
b = c(20, 40, 60),
c = c("oneT", "twoT", "threeT"))
#Create a connection:
con <- DBI::dbConnect(odbc::odbc(),
.connection_string = "Driver={SQL Server};
server=localhost;
database=SAM;
trustedConnection=true;")
#Try to write contents of df to the table using `dbWriteTable`
DBI::dbWriteTable(conn = con,
name = "guest.MikeTestTable",
value = df,
append = TRUE)
#Create a query to read the data from `"guest.MikeTestTable"`:
q <- "SELECT [a]
,[b]
,[c]
FROM guest.MikeTestTable"
##Read the table into R to show that nothing actually got written to the
##table but that it recognizes `guest.MikeTestTable` does exist:
DBI::dbGetQuery(con, q)
[1] a b c
<0 rows> (or 0-length row.names)
I thought this was a weird result so I opened up my SSMS and lo and behold, the table dbo.guest.MikeTestTable
was created. 我认为这是一个奇怪的结果所以我打开了我的SSMS并且看到了
dbo.guest.MikeTestTable
表的创建。 Any help would be much appreciated. 任何帮助将非常感激。
The CRAN release last week (related to the issue @user111417 linked to) resolves this using the new DBI::Id()
function, where the schema and table names are separate and explicit. 上周的CRAN版本(与@ user111417链接的问题相关)使用新的
DBI::Id()
函数解决了这个问题,其中模式和表名是独立且明确的。 Here's an example. 这是一个例子。
library(magrittr)
table_id <- DBI::Id(
schema = "schema_1",
table = "car"
)
ds <- mtcars %>%
tibble::rownames_to_column("car")
# Create the Table
channel <- DBI::dbConnect(
drv = odbc::odbc(),
dsn = "cdw_cache"
)
result <- DBI::dbWriteTable(
conn = channel,
name = table_id,
value = ds,
overwrite = T,
append = F
)
DBI::dbGetQuery(channel, "SELECT COUNT(*) FROM schema_1.car")
# Produces `1 32`
DBI::dbExistsTable(channel, table_id)
# Produces: [1] TRUE
DBI::dbDisconnect(channel)
(Thanks to Daniel Wood for help in https://github.com/r-dbi/odbc/issues/191 .) (感谢Daniel Wood在https://github.com/r-dbi/odbc/issues/191上的帮助。)
请看这里的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.