Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the contents of an .sql file into an R script to run a query?

Tags:

sql

r

postgresql

I have tried the readLines and the read.csv functions but then don't work.

Here is the contents of the my_script.sql file:

SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE HireDate >= '1-july-1993' 

and it is saved on my Desktop.

Now I want to run this query from my R script. Here is what I have:

conn = connectDb()  fileName <- "C:\\Users\\me\\Desktop\\my_script.sql" query <- readChar(fileName, file.info(fileName)$size)  query <- gsub("\r", " ", query) query <- gsub("\n", " ", query) query <- gsub("", " ", query)  recordSet <- dbSendQuery(conn, query) rate <- fetch(recordSet, n = -1)  print(rate) disconnectDb(conn) 

And I am not getting anything back in this case. What can I try?

like image 771
user1367204 Avatar asked Jun 30 '17 19:06

user1367204


People also ask

How do I run a .SQL File in R?

To use SQL, open an R Notebook in the RStudio IDE under the File > New File menu. Start a new code chunk with {sql} , and specify your connection with the connection=con code chunk option. If you want to send the query output to an R dataframe, use output.

Can you use SQL code in R?

You can run SQL code in an R Markdown document. Create a sql code chunk and specify your connection with the connection = con code chunk option. R Markdown provides options that simplify using SQL with R.


1 Answers

I've had trouble with reading sql files myself, and have found that often times the syntax gets broken if there are any single line comments in the sql. Since in R you store the sql statement as a single line string, if there are any double dashes in the sql it will essentially comment out any code after the double dash.

This is a function that I typically use whenever I am reading in a .sql file to be used in R.

getSQL <- function(filepath){   con = file(filepath, "r")   sql.string <- ""    while (TRUE){     line <- readLines(con, n = 1)      if ( length(line) == 0 ){       break     }      line <- gsub("\\t", " ", line)      if(grepl("--",line) == TRUE){       line <- paste(sub("--","/*",line),"*/")     }      sql.string <- paste(sql.string, line)   }    close(con)   return(sql.string) } 
like image 161
Matt Jewett Avatar answered Sep 20 '22 21:09

Matt Jewett