Unable to connect to database using RSQLite - r

So I'm trying to access my DB file without success. Here is my script:
library(DBI)
library(sqldf)
drv <- dbDriver("SQLite")
con <- dbConnect(drv, dbname = "database.sqlite")
and here is the error:
drv <- dbDriver("SQLite")
con <- dbConnect(drv, dbname = "database.sqlite")
Error in rsqlite_connect(dbname, loadable.extensions, flags, vfs) :
Could not connect to database:
unable to open database file
I've checked, of course, and made sure that I've installed the packages correctly and that my working directory is set.

I have solved my problem, and its a bit embarrassing:
I've saved my file on my desktop. since my OS in installed in my native language (Hebrew) the file path had one Hebrew word in it, and while that doesn't pose a problem with reading tables into R, it does pose a problem to the SQL connection.
solving it was easy - I've saved the file in a new folder on my hard drive (c:\database), set as working dir, and everything worked fine.

I can duplicate this error in two ways:
The file exists but you don't have permission to open it
This could be because of operating system permissions. Check your permissions.
The file doesn't exist and you don't have permission to create it.
If SQLite is asked to open a database file that doesn't exist, it tries to create it. If this fails, you get that error message. This will fail if the path to the DB file (in this case the current working directory) does not let you create files. Check your permissions.
Note that if the file does exist but is corrupted, I get a different error:
> con <- dbConnect(drv, dbname = "database.sqlite")
Error in rsqlite_send_query(conn#ptr, statement) :
file is encrypted or is not a database
>
so that's probably not your problem.

I also had this issue. I double checked the path and spotted the mistake there. Once I provided the correct path, the connection worked.
Thanks for this post. It draw my attention to double check if the path was correct.

I ran into a similar problem and the solution was to use forward slashes when issuing dbConnect. I had a working directory defined as "C:\ ..." which worked fine in the rest of my code but not when I tried to open the file with dbConnect.

Related

How do I load data from my SQLite DB into Rstudio?

I created a database with SQL for a schoolproject. Currently I'm stuck at importing this data into rstudio. I put my DB file in this directory: /Users/milanpatty/Documents/Business/Semester_2/R/Proftaak". When I tried to make a connection with this code:
db <- dbConnect(SQLite(), dbname = 'Festivate.db')
I got this error:
Warning message:
Couldn't set synchronous mode: file is not a database
Use `synchronous` = NULL to turn off this warning.
BTW I use DB browser as an interface for SQLite. Could anybody help me with this problem?
edit: I installed the library RSQLite in R

ubuntu to windows find file path r setwd

So I have an Access database that I am trying to see on a windows server 2008 R2 (server name: WrenLab02); this server has the network discovery on, has the folder shared with that title, and is able to be pinged from the ubuntu computer; however now I want to call the folder that the files are in (which I tested on the server itself and works), but on the Ubuntu it keeps saying file directory not found.
On the Ubuntu computer in R:
FilePath <- file.path("//WrenLab02/Clinical/")
if (file.exists(FilePath)) {
setwd(FilePath)
} else {
dir.create(file.path(FilePath))
setwd(FilePath)
}
I know the path exists; I've tried it from another computer (which worked). Even I tried putting "smb://Wrenlab02/Clinical/" as the file director and still the setwd() cannot set the file path.
Maybe I just don't have the folder properly mapped to the Ubuntu, I tried to mount it and it is logged in and I can look at the files inside the folder and indeed the path says smb://WrenLab02/Clinical/. So I don't know where to go from here.
I figured it out; if anyone else is trying to pull files from a windows machine and you are working on a Lynx or Unbuntu machine this code should help you out.
setwd("/run/user/1000/gvfs/smb-share:server=wrenlab02,share=clinical/")
However now I am trying to use odbcConnect from RODBC package; this will connect me to a database from another server
WrenLIS <- '/run/user/1000/gvfs/smb-share:server=wrenlab01,share=administration/DATABASE/CLINICAL DATABASE/PatientContactDB.accdb'
cns <- odbcConnect(dsn="WrenLIS", uid="nferranti", pwd="H0ckey")
but it wont connect I keep getting an error that says:
Warning messages:
1: In RODBC::odbcDriverConnect("DSN=WrenLIS;UID=nferranti;PWD=H0ckey") : [RODBC] ERROR: state IM002, code 0, message [unixODBC][Driver Manager]Data source name not found, and no default driver specified
2: In RODBC::odbcDriverConnect("DSN=WrenLIS;UID=nferranti;PWD=H0ckey") : ODBC connection failed

why would qt still look for db string when its a dsn?

I'm trying to set up dsn with qt and i cant get it to work. The dsn does work with isql.
I'm using ubuntu 12.04
POSTGRES is the dsn.
connection line:
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("POSTGRES");
error:
FATAL: database "POSTGRES" does not exist.
I don't understand why qt doesn't do the look up to find the database behind. i made symlink (usr/local/etc) to odbc.ini and have odbcinst.ini aswell sqli does work with POSTGRES dsn.
Perhaps where will qt look for these files? Googled for 3 days now without success
I kind of gave up cant solve this thank you for any help.
I believe your problem is that you're using the wrong driver. According to the Qt documentation, you need to be using the ODBC driver for DSN files to work - for example:
db = QSqlDatabase::addDatabase("QODBC");
Also note that, again according to the Qt documentation, if you're trying to pass a DSN filename to setDatabaseName, then it MUST have a ".dsn" file extension:
For the QODBC driver, the name can either be a DSN, a DSN filename (in which case the file must have a .dsn extension), or a connection string.
And, finally, it must be listed in your odbc.ini.

R DBI / RPostgreSQL-- connection succeeds but dbListTables returns no tables

The following code connects to my PostgreSQL database successfully (or appears to, at any rate), but attempt to issue queries were met with "relation does not exist" errors, so I tried dbListTables, which doesn't return any tables at all. The database name passed to dbConnect is correct, and the tables do exist. I think the code I'm using is exactly the same as what I was using recently, which worked successfully. Any ideas?
> library(RPostgreSQL)
Loading required package: DBI
> drv <- dbDriver("PostgreSQL")
> con <- dbConnect(drv, dbname="mydb", user="user", password=password)
> dbListTables(con)
character(0)
I'm new to both R and DBI, so I'm sure I could be missing something extremely simple...any help would be appreciated.
Solved-- I was right; it was something incredibly simple (and very, very stupid) on my part. I was running the script from the wrong server. The server I was running it from has an empty copy of the database I was attempting to connect to, so everything succeeded, and the empty result from dbListTables was correct. Once I switched servers (or simply specified the host on the other server), everything worked.
1.Connet to MySQL
a)if Mysql is installed in your system, if not install it.
b)download the RMySQL IN R
library(RMySQL)
drv = dbDriver("MySQL 5.0.1")
make sure MySQL version is correct.
con = dbConnect(drv,host="localhost",dbname="test",user="root",pass="root")
use local host or use the server i.e ip address
use the required database name, user name and password
album = dbGetQuery(con,statement="select * from table")
run required query
close(con)
2.Another way to connect database
a)first install any database like MySQL,Oracle,SQL Server
b)install the ODBC connector for database
library(Rodbc)
channel <- odbcConnect("test", uid="ripley", pwd="secret")
test is the connection name of odbc conector which user has to set manualy
user can find this in Administrator tool
res <- sqlFetch(ch, "table name")
A table can be retrieved as a data frame
res<-sqlQuery(channel, paste("select query"))
part of the with condition one table can be retrieved as a data frame
sqlSave(channel, dataframe)
to save a dataframe to the database(dont use "res<-" something like this)
like user can use
sqlCopy()
sqlDrop()
sqlTables()
close(channel)
always close the connection

Error in gzfile(file, "wb"): cannot open the connection or compressed file

I'm trying to run two things: first, I'm creating a PDF with 4x5, ending with dev.off(), and then trying to create a new graph. However, after starting the second plot, I get:
Error in gzfile(file, "wb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file '/var/folders/n9/pw_dz8d13j3gb2xgqb6rfnz00000gn/T/RtmpTfm1Ur/rs-graphics-822a1c83-b3fd-46c3-8028-4e0778f91d0c/4db4b438-ac35-403b-b791-e781baba152c.snapshot', probable reason 'No such file or directory'
Graphics error: Error in gzfile(file, "wb") : cannot open the connection
What is this error? The working directory is one I have read/write access to, and my hard drive isn't full.
Also, I'm using RStudio.
This is a bit late but for anyone coming here for help, I got this error when I was trying to write a file from RStudio and my destination file path was very long. I realized this could be a problem because when I wrote the file to another location with a shorter name and tried to copy it into my original destination, Windows gave me an error saying "File path too long". You might need to save the original file into another location with a shorter absolute path.
Maybe you should look here. At the end it says
Note:
The most common reason for failure is lack of write permission in the current directory. For save.image and for saving at the end of a session this will shown by messages like
Error in gzfile(file, "wb") : unable to open connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file '.RDataTmp',
probable reason 'Permission denied'
So rapidly, if you try getwd(), look at where is your working directory set. If you're trying to save your document in a place where it's not in your current working directory, it will throw you this error.
At the end of your error message, it says probable reason 'No such file or directory'
Graphics error: Error in gzfile(file, "wb") : cannot open the connection
My diagnosis would be simply that it's trying to save your item in the wrong place and RStudio is not able to find the right place.
This burned me so hopefully saves someone else some toil. The issue was that the classifiers loaded just fine on OS X but on the Linux deployment system they would fail with the error listed in the question. The issue was the the files on the disk had extension abc.RData but the code modelAbc <- readRDS(file="abc.Rdata"). The difference in the upper and lowercase D in the .RData vs .Rdata extension would fail on Linux. It was not very noticeable but check your extensions for case.
You may have no permission to save file in the directory.
On RStudio, get your working directory by getwd().
Then, go to the directory in linux and observe its owner by ls -l.
Now you can change the owner of the directory by chown -R username directoryname.
But you must be root.
Problem resolved by specifying full file path:
saveRDS(df,'C:\\users\\matt\\desktop\\code\\df.Rdata')
I faced this issue lately. Try turning off your anti-virus and build the package, it might help. It worked for me. Usually anti-virus blocks the permissions and you could avoid it by disabling for sometime just before building a package.
I was trying to save an RDS file to my local Dropbox folder so it syncs with my Dropbox.
I figured out I got the same error because I was trying to create a new folder and looks like saveRDS cannot create a new folder, but it can add files to existing folders. So I changed the path to add the file into an existing folder and it worked!
In my case it was Windows Defender which was preventing Rstudio to write any file on hard drive. Either you need to turn Controlled Folder Access off or add Rstudio in the exclusion list.
I also had this problem when working with RStudio and R Markdown. I was getting this error message and had an annoying number of fatal errors which closed RStudio. My issue was that I was working off a network drive and either the name was too long, as in #AHedge above or my network firewalls were giving me trouble. For the moment, I have moved my working files to my desktop and things seem to be working fine. Not sure what this means for my file management over time.
Just want to add more clarity(scenarios in my experience) to what M Beausoleil mentioned.
When you are using a shared-working-directory and trying to rewrite the RDS files which are already existing in a working-directory written by some other user, you get this error.
As some people have already quoted that deleting the existing RDS files or changing the working directory works. It's not a magic. It just works because you are writing a new RDS file and not trying to re-write the old ones.
I came into the same problem after I re-install a new version of RStudio.
The Rmarkdown file I created using old version of RStudio shows the same problem.
When I use ggplot() to draw a picture the error code are as follow:
Warning in gzfile(file, "wb") :
cannot open compressed file 'I:/Rlearning/.Rproj.user/shared/notebooks/58A1385C-PCA作图/1/2C15461A183AC56C/cco192gb0pow1_t\_rs_rdf_32004888ecb.rdf', probable reason 'No such file or directory'
Error in gzfile(file, "wb") : cannot open the connection
Solution:
Create a new Rmarkdown file
Delete all codes
Copy your old Rmarkdown code into it.
I had the same problem.For me, it was caused due to not having enough disk space on the drive where R studio was installed.Freeing up space works.
The reason for the error is that your username is Chinese.Please create new user folder with English in the user directory.For example, you could name the folder for "DavidSmith".Then, you need create three folders("AppData","Local","Temp").File directory C:\Users\DavidSmith\AppData\Local\Temp.
In the Advanced system settings which will modify the environment variables TMP and TEMP C:\Users\DavidSmith\AppData\Local\Temp.Save them.
After modification, open RStudio and try again.
Notice:TMP and TEMP are modified in the USER VARIABLE.
I just ran into this problem after changing my system locale.
Check your locale using Sys.getlocale().
Change it to appropriate one using Sys.setLocale("LC_ALL","ENG") (replace "ENG" with appropriate one)
I can't say with certainty which locale would be appropriate, but it seems to be coherent with default OS one.
Hope this helps!
I had this error because of an invalid character in the filename to be used to save the file, in my case "/" (there are many such characters that cannot be used in a filename). I removed the character and it was solved.
In my case, I received the error "Error in gzfile(file, "wb") : cannot open the connection" when trying to exit R in the Anaconda Prompt and saving workspace image. I am using Windows 10 and R-3.5.2. To fix it, I had to go to the Program Files folder, right click and the R folder, then selected Properties. Selected the Security tab, then, in the Group or user names box, selected Users, then clicked Edit. In the Permissions for Users, I checked Full control and Modify and saved the changes. Then I was able to save the workspace image.
I have another instance of this error which seems to be new (or at least not listed here or here: apparently it's not OK to save a file with the name aux.RData. I guess it's a reserved filename.
x <- rnorm(9000)
save(x, file = "aux.RData")
Error in gzfile(file, "wb") : no se puede abrir la conexión
Also: Warning message:
In gzfile(file, "wb") :
cannot open compressed file 'aux.RData', probable reason 'No such file or directory'
But when I change the filename saves with no problem:
save(x, file = "aux_file.RData")
Haven't seen this case in the other answers:
if this seems to happen all the time, and to be very persistent when it does happen, check the default directory in your file handling software connection.
In my case FileZilla was logging on to my DigitalOcean droplet as "root" and whenever I used FileZilla to create a directory it was setting write permissions to "root", whereas my RStudio on the same droplet read/wrote as "My_Name". Anytime I set something up in FZ (e.g. large imported files, renamed or copied) the permissions would switch and I'd get this error.
If this is what is causing frequent error messages it can be solved instantly with chown -R My_Name directoryname but in the longer run, if you are going to be using your file handler to define and create a lot of directories, it will pay to create a connection whose default name is the same name you use for RStudio.
In my case, when it happened first, months ago, the solution here worked.
But recently, it came back, constantly... What solved this time was to change the anti-virus. I have not just the Windows defender, but also a 2nd anti-virus, the same in both times. I ended up deinstalling it and installing another antivirus... After this, the problem did not happen again...
After several days trying to solve this same ERROR or problem in my case (Windows 10 and R), I tried to save my file(file.RData) in D disk instead of C disk (where I always was working and I have installed R) and it was fine, without problems,my file was saved in D:/Users.When I tried many times to save it in C disk, always gave me Permission denied.
save(Myfile, file="D:/Users/Myfile.RData")
I encountered this same issue when trying to save an Rds file from an Markdown file. Changing my relative file path to an absolute file path worked for me.
In my case, this error was because the file that I wanted to re-write, was read-only (for whatever reason, I didn't do it myself). I just right-click on the file's name in the folder and unchecked the read-only property. After that it worked.

Resources