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)
}
Related
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
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 ?
Select * from table_A WHERE name in (#nameObj)
My issue is I am passing this object from code behind as
#nameObj = "'" + "john" + "'" + "," + "'" + "joseph" + "'"
So I want my final query like this:
Select * from table_A WHERE name in ('john','joseph')
But it is giving query like this:
Select * from table_A WHERE name in ('''john'',''joseph''')
This work for me
sql = $#" AND Office IN ('{string.Join("','", new string[] { "aa", "bb"})}')";
But you should pass this as sql parameter;
in sql query you have
AND Office IN (#datain)
and in call query
_dbContext.Offices.FromSql(sql,
new NpgsqlParameter(
"#datain",
$#"'{string.Join("','", new string[] {"aa", "bb"})}')")
)
.ToList();
I have created a combobox in javafx and I want to query the sqlite db for data which are greater or less than what is selected from the combobox.
Combobox have ObservableList "10,20,30,40,50"
My query is " Select * From table Where age ( xxx ) ?"
xxx can be (" >=" or "<=")
this is my query
String qry_age = "Select * From table Where age (>=) ?";
PreparedStatement ps_age = connect.prepareStatement(qry_age);
ps_age.setInt(1,15);
ResultSet rs_age = ps_age.executeQuery();
while (rs_age.next()) {
System.out.println(rs_age.getString("age"));
}
You could simply use string concatenation to construct the query:
String ageCompareOperator = ">="; // or something else e.g. value from ComboBox
String qry_age = "Select * From table Where age " + ageCompareOperator + " ?";
PreparedStatement ps_age = connect.prepareStatement(qry_age);
...
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"] = ...