RSQLite - dbWriteTable - field.type - 如何获得正确的日期格式?

问题描述 投票:0回答:3

RSQLite::dbWriteTable
函数,正确地将日期从
df
传递到db

我的 df 上有一些日期字段,当我尝试使用上述函数并设置 field.types = c(col1 = "Date", col2 = "Date")

SQLite
数据库上写入表时,它将这些日期字段写入数字而不是日期,例如:

"2018-12-01"
变成
17866

这是我的完整代码:

dbWriteTable(db, "table", df, overwrite = T, append = F, 
          field.types = c(Col1 = "Date", Col2  = "Date"))

这实际上将

"table"
写在
SQLite
db
上,并为此类列使用正确的
Date
格式,但单元格内的值不是日期,它们仍然是数字,例如
17866

在这里我发现有人提出了一种解决方法,将日期转换为.character。

是否有正确的方法将date值传递给SQLite db

提前谢谢您

r rsqlite
3个回答
1
投票

现在回顾一下,我实际上从未找到一种方法来做到这一点,正如我的问题所描述的那样。最后我采用了我在问题中提到的解决方法:

在 SQLite 上写入之前转换文本中的所有日期变量 数据库。


0
投票

“extended_types”参数可能适用于 DBconnection。

db <- DBI::dbConnect(RSQLite::SQLite(),
                     dbname = "xxx",
                     extended_types = T) # this point

0
投票

只是想说@koinobori 的解决方案确实有效,尽管它被否决了。完整解决方案:

# Create a db connection and mtcars db
conn <- dbConnect(
  drv = RSQLite::SQLite()
  ,"mtcars.db"
  ,extended_types = TRUE
)

# Create data with date column
mtcars$dt <- Sys.Date()

# Create a table in mtcars.db called mtcars_tbl
dbWriteTable(
  conn = conn
  ,name = "mtcars_tbl"
  ,value = mtcars
)

df <- dbGetQuery(
  conn = conn
  ,statement = "
  SELECT *
  FROM mtcars_tbl
  "
)

str(df)
'data.frame':   32 obs. of  12 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
 $ dt  : Date, format: "2024-05-02" "2024-05-02" "2024-05-02" "2024-05-02" ...
© www.soinside.com 2019 - 2024. All rights reserved.