SQL and r ”update fields” - sql

SQL and r ”update fields”
Can anyone help Me.? i am trying to update fields in a row in a table on a sql server.
I have tried to send a vector with that contains the data I want to update(new_d), but I get an error every time I try to send the object with sql query. If I hardcode it, it works fine and the update goes through to the server.
what goes wrong when it does not want to send the object and what does it take to make it work? so it can save the update to the server
Hope anyone can show me what i do worng.
library(tidyverse)
library(readxl)
library(DT)
library(RODBC)
library(DBI)
library(odbc)
library(dbplyr)
# Connection is working ---------------------------------------------------
conn <- dbConnect(odbc(),
Driver = "ODBC Driver 13 for SQL Server",
Server = "IP, PORT",
Database = "DBNAME",
UID = "USERNAME",
PWD = "PASSWORD")
new_d <- c(name = 'Rap',
dateOfBirth = '1938-06-06',
city = 'Hollywood',
gender = 'Man',
time() = 8,
feeling = 'Happy')
# NOT WORKING -------------------------------------------------------------
update_statement1 <- build_sql("UPDATE ShinyTest
SET Name =?, City =?, Gender =?,
DateOfBirth =?, Time =?, Feeling =?
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement1
# NOT WORKING -------------------------------------------------------------
update_statement2 <- build_sql("UPDATE ShinyTest
SET Name = name, City = city, Gender = gender,
DateOfBirth = dateOfBirth, Time = time, Feeling = feeling
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement2
# NOT WORKING -------------------------------------------------------------
update_statement3 <- build_sql("UPDATE ShinyTest
SET Name = 'name', City = 'city', Gender = 'gender',
DateOfBirth = 'dateOfBirth', Time = 'time', Feeling = 'feeling'
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement3
# NOT WORKING -------------------------------------------------------------
update_statement4 <- build_sql("UPDATE ShinyTest
SET Name = $name, City = $city, Gender = $gender,
DateOfBirth = $dateOfBirth, Time = $time, Feeling = $feeling
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement4
# WORKING -------------------------------------------------------------
update_statement5 <- build_sql("UPDATE ShinyTest
SET Navn = 'Rap', City = 'Hollywood', Gender = 'Mand',
DateOfBirth = '1938-06-06', Tid = '8', Feeling = 'Glad'
WHERE ShinyUserID = 4", con = conn)
update_statement5
# NOT WORKING -------------------------------------------------------------
DBI::dbSendQuery(conn, update_statement1)
DBI::dbSendQuery(conn, update_statement2)
DBI::dbSendQuery(conn, update_statement3)
DBI::dbSendQuery(conn, update_statement4)
# WORKING -------------------------------------------------------------
DBI::dbSendQuery(conn, update_statement5)
DBI::dbDisconnect(conn)
# The Error i get ---------------------------------------------------------
#Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'Rap'. [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared.
#<SQL> 'UPDATE ShinyTest
# SET Navn = navn, City = city, Gender = gender,
# DateOfBirth = dateOfBirth, Tid = tid, Feeling = feeling
# WHERE ShinyUserID = 4('Rap', '1938-06-06', 'Hollywood', 'Mand', '8', 'Glad')'

Related

Select data from MySQL database and put in R dataframe

I can access a MySQL database and store output to an R dataframe using the following script where sam_pn = walker
con <- dbConnect(MySQL(),
user = user,
password = password,
host = host,
dbname = dbname)
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'walker'")
But what i would like to do is store 'walker' as an R value pn and then use pn value in the sql query like below so i can vary the pn value.... but it does not work. The syntax is not right. Note sam and che are tables in the database
pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'pn'")
pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = ?",
params = list(pn))
This is what worked in the end
pn = 'walker'
data = dbGetQuery(con, paste0("SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = '", pn ,"'"))

Creating Multiple SQL Tables based on the factors from a column

I am trying to create a SQLite table for each factor that I have in a R dataframe. I have created a for loop in an attempt to accomplish this, but when I include the dWriteTable() function it gives me an error. I believe it might have something to do with the "argument" but I can't say for certain.
Here is the code I currently have with the for loop:
# Connects to the database##
mydb <- dbConnect(RSQLite::SQLite(), "../Output/all_data.sqlite")
#Reads the selected table in database
mu_ut <- dbReadTable(mydb, "mu_ut")
for(i in unique(mu_ut$AnimalID)){
AnID <- paste("AnID", i, sep = ".")
dfname <- assign(AnID, mu_ut[mu_ut$AnimalID == i,])
dbWriteTable(conn = mydb, name = dfname, value = dat_csv,
field.types = c(DateAndTime = "DATETIME",
AnimalID = "CHAR",
Species = "CHAR",
Sex = "CHAR",
CurrentCohort = "CHAR",
BirthYear = "DATE",
CaptureUnit = "CHAR",
CaptureSubunit = "CHAR",
CaptureArea = "CHAR"))
}
I get the error message when I run it:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘dbWriteTable’ for signature ‘"SQLiteConnection", "data.frame", "data.frame"’
Any help would be appreciated!
Thank you!
When using dbWriteTable :
name is a character string giving the name of the table.
value is a dataframe with the values to write into the table
Try:
dbWriteTable(conn = mydb, name = AnID, value = mu_ut[mu_ut$AnimalID == i,],
field.types = c(DateAndTime = "DATETIME",
AnimalID = "CHAR",
Species = "CHAR",
Sex = "CHAR",
CurrentCohort = "CHAR",
BirthYear = "DATE",
CaptureUnit = "CHAR",
CaptureSubunit = "CHAR",
CaptureArea = "CHAR"))

Calling sql from R

con <- dbConnect(odbc::odbc(),
Driver = "xxx",
Server = "xxxx",
Database = "xx", uid = "xxx", pwd = "xxx")
ABove is the function to call sql queries
and below is the code to call the table in R
fac <- dbGetQuery(con, "(select * from table where Category = '",input$Cat,"')") ##input$Cat is called in UI.R
But the above statement is not getting executed. Am i calling '",input$Cat,"' wrongly ?

show sql data from User input

The code below inserts whatever data is typed into the text fields: name1 and phone1 into my database and I need to be able to type in stored data and retrieve it
def insert():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO people(name, phone) VALUES(?,?)',(name1, phone1,))
db.close()
but=Button(root,padx=2,pady=2,text='Submit',command=insert,font=('none 13 bold'))
but.place(x=60,y=100)
I need to retrieve the records by typing them into the same text field and then print them out. So far I have this but Im confused with the SQL.
def show():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM people(name, phone) VALUES(?,?)',(name1, phone1,))
for row in cursor.fetchall():
print(row)
res=Button(root,padx=2,pady=2,text='Show',command=show,font=('none 13 bold'))
res.place(x=160,y=100)
Use:
cursor.execute('''INSERT INTO students(name, phone) VALUES(?,?)''',[(name1), (phone1)])
and:
cursor.execute("SELECT * FROM students WHERE name = ? AND phone = ?", [(name1),(phone1)])
Newcode:
def insert():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('''INSERT INTO students(name, phone) VALUES(?,?)''',[(name1), (phone1)])
db.close()
def show():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name = ? AND phone = ?", [(name1),(phone1)])
for row in cursor.fetchall():
print(row)
res=Button(root,padx=2,pady=2,text='Show',command=show,font=('none 13 bold'))
res.place(x=160,y=100)

Solution to this error

I have written this query:
String sql = "Update db " +
"SET LName = '"+txtLName.getText()+"'," +
"ATC_Code = '"+txtATCcode.getText()+"'," +
"ATC_Name= '"+txtATCname.getText()+"'," +
"Course_Name = '"+txtCourseName.getText()+"'," +
"Course_Fee = '"+txtCourseFee.getText()+"'," +
"Where FName = '"+txtFName.getText()+"' ";
And I got an error like:
Malformed SQL Statement: Expected ',', found 'Anuja'`.
Statement:Update db SET LName = 'df',ATC_Code = '323',ATC_Name= 'sd',Course_Name = 'd',Course_Fee = '534',Where FName = 'Anuja'
Remove last , for Set statement:
String sql = "Update db " +
"SET LName = '"+txtLName.getText()+"'," +
"ATC_Code = '"+txtATCcode.getText()+"'," +
"ATC_Name= '"+txtATCname.getText()+"'," +
"Course_Name = '"+txtCourseName.getText()+"'," +
"Course_Fee = '"+txtCourseFee.getText() + //here does not need '
"Where FName = '"+txtFName.getText()+"' ";
On a side note, this kind of sql command generation(concatenating strings that contains some values) are suspect to SQL injection attacks, to prevent this type of attacks, use paramaters and set the parameters values instead. See SQL injection for more information.
Update db
SET LName = 'df',
ATC_Code = '323',
ATC_Name= 'sd',
Course_Name = 'd',
Course_Fee = '534',
Where FName = 'Anuja'
Only will change remove last comma ','
Update db
SET LName = 'df',
ATC_Code = '323',
ATC_Name= 'sd',
Course_Name = 'd',
Course_Fee = '534'
Where FName = 'Anuja'