R Multiline statement when using RSQLite - r

I am having a transaction that needs to run on sqlite. The Transaction includes several queries. If built separately (line by line) it works but it requires the call of dbSendQuery n-times. It slows down the code quite a bit.
The ideal code should look like this, but multiline query fails:
library("RSQLite")
con <- dbConnect(RSQLite::SQLite(), dbname="test.db")
dbSendQuery(con, paste("CREATE TABLE Variables (Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT)"))
dbSendQuery(con, paste("INSERT INTO Variables (Name) VALUES ('newid');"))
dbSendQuery(con, paste("BEGIN IMMEDIATE TRANSACTION;",
"UPDATE Variables SET TextValue = '0' WHERE Name = 'newid';",
"UPDATE Variables SET RealValue = 0 WHERE Name = 'newid';",
"UPDATE Variables SET IntegerValue = 0 WHERE Name = 'newid';",
"COMMIT;",sep=" "))
a <- dbFetch(dbSendQuery(con, paste("SELECT * FROM _Variables;")))
dbSendQuery(con, paste("COMMIT;"))

Consider the RSQLite methods: dbBegin() and dbCommit() (w/ dbRollback for any errors) to handle transactions. Even consider combining all UPDATE statements into one:
library("RSQLite")
con <- dbConnect(RSQLite::SQLite(), dbname="test.db")
dbSendStatement(con, "CREATE TABLE [Variables] ([Name] TEXT PRIMARY KEY, [RealValue] REAL, [IntegerValue] INTEGER, [BlobValue] BLOB, [TextValue] TEXT)")
dbSendStatement(con, "INSERT INTO [Variables] ([Name]) VALUES ('newid')")
dbBegin(con)
tryCatch({
dbSendStatement(con, "UPDATE [Variables] SET TextValue = '0', RealValue = 0, IntegerValue = 0 WHERE [Name] = 'newid'")
}, error=function(e) dbRollback(con))
dbCommit(con)
a <- dbGetQuery(con, "SELECT * FROM [Variables]")
You can even combine UPDATE statement into one query:

Related

Bulk update Oracle sql table with random guid

I need to update multiple rows of a PLSQL table, something like this:
StringBuilder stringBuilder = new StringBuilder(
"UPDATE review_item SET LAST_MODIFIED_TIMESTAMP = systimestamp, ")
.append("target_urn = ?, ")
.append("assignee_urn = NULL WHERE item_id in (")
.append(StringUtils.join(itemIds, ","))
.append(")");
PreparedStatement ps = connection.prepareStatement(stringBuilder.toString());
OracleUtil.bindInput(ps, 1, getRandomUuid(), dbClauses.getQueuePostCleanState());
Issue is - I need all the rows to get updated with a different random guid, in this case it is getting updated with the same one. Any way to do this?

Join a data frame (or other R object) to a table in a read-only Postgresql database?

I have read-only access to a Postgres database. I can not write to the database.
Q. Is there a way to construct and run a SQL query where I join a data frame (or other R object) to a table in a read-only Postgres database?
This is for accessing data from WRDS, https://wrds-www.wharton.upenn.edu/
Here's an attempt at pseudocode
#establish a connection to a database
con <- dbConnect( Postgres(),
host = 'host.org',
port = 1234,
dbname = 'db_name',
sslmode = 'require',
user = 'username', password = 'password')
#create an R dataframe (or other object)
df <- data.frame( customer_id = c('a123', 'a-345', 'b0') )
#write a sql query we will run
sql_query <- "
SELECT t.customer_id, t.* FROM df t
LEFT JOIN table_name df
on t.customer_id = df.customer_id
"
my_query_results <- dbSendQuery(con, sql_query)
temp <- dbFetch(res, n = 1)
dbClearResult(res)
my_query_results
Note and edit: The example query I provided is intentionally super simple for example purposes.
In my actual queries, there might be 3 or more columns I want to join on, and millions of rows I want to join on.
Use the copy_inline function from the dbplyr package, which was added following an issue filed on this topic. See also the question here.
An example of its use is found here.
If your join is on a single condition, it can be rewritten using an in clause:
In SQL:
SELECT customer_id
FROM table_name
WHERE customer_id in ('a123', 'a-345', 'b0')
Programmatically from R:
sql_query = sprintf(
"SELECT customer_id
FROM table_name
WHERE customer_id in (%s)",
paste(sQuote(df$customer_id, q = FALSE), collapse = ", ")
)

Unknown error in sqldf package

What does this error mean?
Closing open result set, pending rowsError in result_create(conn#ptr, statement) : near "(": syntax error
This appears when i want to run the code
```{r}
library(sqldf)
first <- dbConnect(SQLite(), dbname= "DATA.sqlite")
dbSendQuery(conn = first,
"CREATE TABLE COMPANY_MASTER
(
CompId INTEGER,
CompName TEXT,
Address TEXT,
DirectorName TEXT,
EmployeeNo INTEGER,
PRIMARY KEY(CompName)
)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1001,'Infosys','ABC1927','Dr.Sandeep',128)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1002,'Cognizant','ERT654','Michael',156)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1003,'Tata','PCD531','Sancheti',113)")
*
dbSendQuery(conn = first,
"CREATE TABLE INCOME
(
CompName TEXT,
In(2016) INTEGER,
In(2017) INTEGER,
In(2018) INTEGER,
FOREIGN KEY(CompName)
*
)")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('518361','528464','538646')")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('218434','205314','225815')")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('1038434','1184344','128434')")
CompMAst <- dbGetQuery(conn = first, "SELECT * FROM COMPANY_MASTER")
Income <- dbGetQuery(conn = first, "SELECT * FROM INCOME")
```
While giving the above error in the
dbSendQuery(conn = first,
"CREATE TABLE INCOME
(
CompName TEXT,
In(2016) INTEGER,
In(2017) INTEGER,
In(2018) INTEGER,
FOREIGN KEY(CompName)
)")
region of the code. What does this error mean? Is it some specific format error? Or have i missed some chunk that had to be mentioned before executing. Or is some other package involved Please help.
According to #SatZ and the error of you giving four columns and entering three values your ideal code should be
```{r}
library(sqldf)
first <- dbConnect(SQLite(), dbname= "DATA.sqlite")
dbSendQuery(conn = first,
"CREATE TABLE COMPANY_MASTER
(
CompId INTEGER,
CompName TEXT,
Address TEXT,
DirectorName TEXT,
EmployeeNo INTEGER,
PRIMARY KEY(CompName)
)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1001,'Infosys','ABC1927','Dr.Sandeep',128)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1002,'Cognizant','ERT654','Michael',156)")
dbSendQuery(conn = first, "INSERT INTO COMPANY_MASTER
VALUES(1003,'Tata','PCD531','Sancheti',113)")
dbSendQuery(conn = first,
"CREATE TABLE INCOME
(
CompName TEXT,
IN_2016 TEXT,
IN_2017 TEXT,
IN_2018 TEXT)")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('Infosys','5183.61','5284.64','5386.46')")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('Cognizant','2184.34','2053.14','2258.15')")
dbSendQuery(conn = first, "INSERT INTO INCOME
VALUES('Tata','10384.34','11843.44','1284.34')")
CompMAst <- dbGetQuery(conn = first, "SELECT * FROM COMPANY_MASTER")
Income <- dbGetQuery(conn = first, "SELECT * FROM INCOME")
```
The dbSendQuery() method returns a "DBIResult" object, it's the caller's responsibility to clear it with dbClearResult(). For queries that don't return a result set, use dbExecute() instead of dbSendQuery() to avoid the warning. (dbExecute() is the equivalent of dbGetQuery() for queries that don't return a result set.)
See the help to dbBind() for use cases of the longer form dbSendQuery() + dbFetch() + dbClearResult().

Error cound not find all functions in the R program

This is the program however when I run it says cannot find function dbSendQuery or dbCoonect or any function in the program.I am not sure is it due to me not installing the right packages
install.packages("RMySQL")
library(RMySQL)
mydb <- dbConnect(MySQL(), dbname='W1547901_0', user='',password='',host='elephant.ecs.westminster.ac.uk')
dbSendQuery(mydb, "drop table if exists books")
# creating tables in bookstore:
dbSendQuery(mydb, "
CREATE TABLE books (
book_id INT,
title VARCHAR(50),
publisher VARCHAR(50));")
dbListTables(mydb)
dbSendQuery(mydb, "INSERT INTO books
(book_id, title, publisher)
VALUES(1, 'R and MySQL', 'Addison Wesley');")
try1 = fetch(dbSendQuery(mydb, "SELECT book_id, title, publisher
FROM books
WHERE book_id = 1 ;"))

RMySQL retrieving data from database table basing on an if statement

I am trying to retrieve data from a database table based on a given condition:
I want to select all from a table, and during the while loop I put a condition like to return only what I want the way it is done in PHP
mytable <- dbSendQuery(con, "select date from member")
while(!dbHasCompleted(mytable)){
if(name = 'myname'){
new_date <- dbFetch(mytable, n=-1)
print(mytable)
}
}
How do I deal with the if statements to operate well?
I later found out the solution like this
mytable <- dbSendQuery(con, "select * from member")
while(!dbHasCompleted(mytable)){
new_date <- dbFetch(mytable, name = 'john', n=-1)
print(new_date )
}

Resources