Calling sql from R - sql

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 ?

Related

SQL and r ”update fields”

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')'

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"))

Julia ReadOnlyMemoryError with ODBC SQL query

I'm working on writing a function that queries a SQL database and I'm encountering a ReadOnlyMemoryError() that has me stumped. The issue is that when I run my code as a simple script everything functions as expected. But when I try to wrap the exact same code in a function I get the ReadOnlyMemoryError().
Here's the script version of my code:
using ODBC
using DBInterface
using Dates
using DataFrames
server = "server string "
username = "username "
password = " password"
db = " db name"
start_date=Nothing
end_date=Nothing
if start_date == Nothing || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if end_date == Nothing || typeof(end_date) != "Date"
end_date = Dates.today()
end
query = """ SQL SELECT statement """
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
df = DBInterface.execute(conn, query) |> DataFrame
This works as expected, the result is a dataframe df with about 500k rows. However, when I try use this same code to make a reusable function I get the error:
using ODBC
using DBInterface
using Dates
using DataFrames
function get_cf_data(start_date=Nothing, end_date=Nothing)
server = " server string "
username = " user name"
password = " password"
db = " db "
if start_date == Nothing || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if end_date == Nothing || typeof(end_date) != "Date"
end_date = Dates.today()
end
query = """ SQL SELECT statement """
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
df = DBInterface.execute(conn, query) |> DataFrame
return df
end
In this case, when I try to call from REPL get_cf_data() I get ERROR: ReadOnlyMemoryError(). I'm somewhat new to Julia, so any insight would be very much appreciated. Thank you!
As commented, best practice in most programming languages when integrating APIs like ODBC connections is to close and release its resource after usage.
Additionally, consider parameterization (best practice in any language running SQL that passes literal values) where you set up a prepared SQL statement and bind values in a subsequent execute call.
function get_cf_data(start_date=Nothing, end_date=Nothing)
server = " server string "
username = " user name"
password = " password"
db = " db "
if isnothing(start_date) || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if isnothing(end_date) || typeof(end_date) != "Date"
end_date = Dates.today()
end
# PREPARED STATEMENT WITH QMARK PLACEHOLDERS
sql = """SELECT Col1, Col2, Col3, ...
FROM myTable
WHERE myDate BETWEEN ? AND ?
"""
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
# PREPARE STATEMENT AND BIND PARAMS
stmt = DBInterface.prepare(conn, sql)
df = DBInterface.execute(stmt, (start_date, end_date)) |> DataFrame
DBInterface.close(stmt) # CLOSE STATEMENT
DBInterface.close(conn) # CLOSE CONNECTION
stmt = Nothing; conn = Nothing # UNINTIALIZE OBJECTS
return df
end

Upper Function Input parameter in Oracle

I try to prevent SQL injection in SQL query. I used following code to do it but unfortunately I faced some problem. The query is not running in oracle DB:
strQuery = #"SELECT PASSWORD FROM IBK_USERS where upper(user_id) =upper(:UserPrefix) AND user_suffix=:UserSufix AND STATUS_CODE='1'";
//strQuery = #"SELECT PASSWORD FROM IBK_CO_USERS where user_id = '" + UserPrefix + "' AND user_suffix='" + UserSufix + "' AND STATUS_CODE='1'";
try
{
ocommand = new OracleCommand();
if (db.GetConnection().State == ConnectionState.Open)
{
ocommand.CommandText = strQuery;
ocommand.Connection = db.GetConnection();
ocommand.Parameters.Add(":UserSufix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserSufix"].Value = UserSufix;
ocommand.Parameters.Add(":UserPrefix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserPrefix"].Value = UserPrefix.ToUpper();
odatareader = ocommand.ExecuteReader();
odatareader.Read();
if (odatareader.HasRows)
{
Your parameters shouldn't contain the semicolon :. This is just an indicator in your query that the variable that follows is a parameter, but you don't have to supply that on the .NET side:
ocommand.Parameters["UserSufix"] = ...

How to pass arguments to a function to connect to database

I would like to create a function to connect to a SQLite database by passing it two parameters: database name and table.
I tried this:
sqLiteConnect <- function(database, table) {
con <- dbConnect("SQLite", dbname = database)
query <- dbSendQuery(con, "SELECT * FROM ", table)
fetch(query, n = -1)
}
But I pass result <- sqLiteConnect(primary_database, "table_name") I get Error in sqliteExecStatement(conn, statement, ...) : RS-DBI driver: (error in statement: near " ": syntax error)
If I change my function to
sqLiteConnect <- function(database, table) {
con <- dbConnect("SQLite", dbname = database)
query <- dbSendQuery(con, "SELECT * FROM ", table, "")
fetch(query, n = -1)
}
I get Error in sqliteExecStatement(conn, statement, ...) : unused argument ("")
I guess the problem is in concatenating a variable to a string.
dbSendQuery requires the SQL statement as a single character string (it does not take the table as an argument), so you would need to create it using either paste() or sprintf(), for example:
sqLiteConnect <- function(database, table) {
con <- dbConnect("SQLite", dbname = database)
query <- dbSendQuery(con, paste("SELECT * FROM ", table, ";", sep=""))
fetch(query, n = -1)
}