Can't connect to SQLlite database

447 Views Asked by At

When trying to connect to this database by copying their code I get the error:

"Could not connect to database: unable to open database file"

The code :

tidy_finance <- dbConnect(
  SQLite(),
  "data/tidy_finance.sqlite",
  extended_types = TRUE
)
1

There are 1 best solutions below

0
On

Collecting comments to an answer.

dbConnect(SQLite(),"data/tidy_finance.sqlite",extended_types = TRUE)

Either opens the existing data/tidy_finance.sqlite file or if the file is missing, creates an empty database. Problem arises when it can't find existing data/ directory. One could just remove directory from sqlite file path, but we can also check and create the missing folder in R before attempting to create / open sqlite file.:

library(RSQLite)
library(dbplyr)

list.files(include.dirs = T, recursive = T)
#> [1] "sqlite_test.R"
# no data/ in working directory
# dbConnect() will fail:
tidy_finance <- dbConnect(SQLite(), "data/tidy_finance.sqlite",extended_types = TRUE)
#> Error: Could not connect to database:
#> unable to open database file


# create the directory if missing, open and close db connection, check file listing
if (!dir.exists("data/")){
  dir.create("data/")
}
tidy_finance <- dbConnect(SQLite(), "data/tidy_finance.sqlite",extended_types = TRUE)
dbDisconnect(tidy_finance)
list.files(include.dirs = T, recursive = T)
#> [1] "data"                     "data/tidy_finance.sqlite"
#> [3] "sqlite_test.R"

Created on 2022-10-14 with reprex v2.0.2