如何从SQLite数据库导入?

fivyi3re  于 2022-11-24  发布在  SQLite
关注(0)|答案(3)|浏览(231)

我有一个从Scraperwiki导出的SQLite数据库文件,文件扩展名为.sqlite。我如何将它导入R,大概是将原始数据库表Map到单独的数据框中?

daupos2t

daupos2t1#

您可以使用RSQLite套件。
一些示例代码将整个数据存储在data.frame中:

library("RSQLite")

## connect to db
con <- dbConnect(drv=RSQLite::SQLite(), dbname="YOURSQLITEFILE")

## list all tables
tables <- dbListTables(con)

## exclude sqlite_sequence (contains table information)
tables <- tables[tables != "sqlite_sequence"]

lDataFrames <- vector("list", length=length(tables))

## create a data.frame for each table
for (i in seq(along=tables)) {
  lDataFrames[[i]] <- dbGetQuery(conn=con, statement=paste("SELECT * FROM '", tables[[i]], "'", sep=""))
}
clj7thdc

clj7thdc2#

对于其他看到这篇文章的人来说,使用purr库从顶部答案开始循环的一个好方法是:

lDataFrames <- map(tables, ~{
  dbGetQuery(conn=con, statement=paste("SELECT * FROM '", .x, "'", sep=""))
})

也就意味着你不用做:

lDataFrames <- vector("list", length=length(tables))
pn9klfpd

pn9klfpd3#

将sgibb和primaj的答案放在一起,命名表,并添加工具以检索所有表或特定表:

getDatabaseTables <- function(dbname="YOURSQLITEFILE", tableName=NULL){
  library("RSQLite")
  con <- dbConnect(drv=RSQLite::SQLite(), dbname=dbname) # connect to db
  tables <- dbListTables(con) # list all table names

  if (is.null(tableName)){
    # get all tables
    lDataFrames <- map(tables, ~{ dbGetQuery(conn=con, statement=paste("SELECT * FROM '", .x, "'", sep="")) })
    # name tables
    names(lDataFrames) <- tables
    return (lDataFrames)
  }
  else{
    # get specific table
    return(dbGetQuery(conn=con, statement=paste("SELECT * FROM '", tableName, "'", sep="")))
  }
}

# get all tables
lDataFrames <- getDatabaseTables(dbname="YOURSQLITEFILE")

# get specific table
df <- getDatabaseTables(dbname="YOURSQLITEFILE", tableName="YOURTABLE")

相关问题