My SQL query which runs perfectly in terminal looks like this:
select t.txid, t.from_address, t.to_address, t.value, t.timestamp,
t.conformations, t.spent_flag,t.spent_txid from transaction_details t
where t.to_address =(select distinct a.address from address_master a
inner join panel_user p on a.user = p.user and a.user= "auxesis");
Now I tried using it in Django like this:
sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from
transaction_details t where t.to_address =(select distinct a.address from
address_master a inner join panel_user p on a.user = p.user and a.user= "%s" """),%(user)
cursor.execute(sql)
res = cursor.fetchall()
But ya its not working. So any one please help me with it?
You're trying to use string formatting to build an SQL query. Don't do that, use parameterized queries. If you do that, you don't add quotes around the placeholders, the database connector will handle escaping of the parameters for you. Just pass the arguments as a tuple:
sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from
transaction_details t where t.to_address =(select distinct a.address from
address_master a inner join panel_user p on a.user = p.user and a.user = %s """)
cursor.execute(sql, (user,))
res = cursor.fetchall()
Related
I am working on sql queries in python using PyMySQL. Lets say we have the following function
def f(bid)
con=connection()
cursor=con.cursor
sql = "select b.text from book b where b.id = 'bid'"
cursor.execute(sql)
book_text = cursor.fetchone()
print (book_text)
When I do:
f('123abc')
It prints:
()
But If I replace the above sql query with:
"select b.text from book b where b.id = '123abc'"
It prints the right thing.
Any ideas? Thanks in advance!
You need to 'bind' the parameter to the query:
sql = "select b.text from book b where b.id = %s"
cursor.execute(sql, (bid, ))
Note: The benefit of using placeholders (%s) in the query and passing an additional object to execute() usually handles all different variable types (int, str, dates, ...) for you.
Have a look at the docs which objects you can pass to execute().
you '123abc' argument isn't modifying the string you are using for your sql query.
change to:
sql = "select b.text from book b where b.id = '{}'".format(bid)
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.
Expected Output:
('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
Script:
import psycopg2
# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()
sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print('Counts:',result)
conn.close()
Current output:
[root#pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
Any help is appreciated.
Thanks!
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:
a table name cannot be a parameter in SQL
the input only comes from the program itself and is fully mastered
Possible code:
sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']
for t in tables:
cursor.execute(sql.format(t))
result = cursor.fetchall()
print("('", t, "':,", result, ")")
I believe something as below, Unable to test code because of certificate issue.
sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
for name, count in cursor:
print ("")
Or
sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print(result)
I need a way to fetch similar records from DB using LIKE from Django .
My code is :
def fetchProductsDate1(request):
query = request.session.get('query')
date1 = request.session.get('date1')
db = pymysql.connect(host=host,user=user,passwd=passwd,db=dbName)
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
stmt = "SELECT FSN FROM tab WHERE query LIKE '%s' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)
log.info(stmt)
cur.execute(stmt)
rows = cur.fetchall()
json_data = rows[0][0]
The db statement looks like:
SELECT num FROM tab WHERE query LIKE 'soch sarees' AND DATE(updated_at) LIKE '2018-11-14'
I want the statement to be like :
SELECT num FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'
Any help will be really nice :)
Thanks.
You can use %% to do that
stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%s%%' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)
Which will give us
SELECT FSN FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'
Also, I think it' a bad practice to concat parameters like this.This opens path to SQL Injection
You could try:
select_stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%(name)%%%' AND DATE(updated_at) LIKE '%(date)%'"
cursor.execute(select_stmt, { 'name': 'soch sarees','date':'2018-11-14' })
I want to fetch all rows from MySQL table with
query = "SELECT * FROM %s WHERE last_name=%s"
cursor.execute(query, ("employees","Smith"))
but I'm getting
You have an error in your SQL syntax. When I try
query = "SELECT * FROM employees WHERE last_name=%s"
cursor.execute(query, ("Smith",))
all is fine.
Documentation says
cursor.execute(operation, params=None, multi=False)
The parameters found in the tuple or dictionary params are bound to the variables in the operation.link on docs
The first will generate an SQL like this:
SELECT * FROM 'employees' WHERE last_name='smith'
The parameters are SQL quoted.
If you really need to have a table name as param, you must proceed in 2 steps:
table_name = 'employees'
query_tpl = "SELECT * FROM {} WHERE last_name=%s"
query = query_tpl.format(table_name)
cursor.execute(query, ("Smith",))
you need to add the quote symbol. So the query will be like
SELECT * FROM employees WHERE last_name='Smith'
Change both your query to
query = "SELECT * FROM %s WHERE last_name='%s'"
query = "SELECT * FROM employees WHERE last_name='%s'"
You can't use a parameter for the table name in the execute call.
But you can use Python string interpolation for that:
query = "SELECT * FROM %s WHERE last_name=%s" %("employees","Smith")
cursor.execute(query)
You can't use a table name as a parameter. you are generating invalid sql with your code that is putting quotes around each string. the table name cannot have quotes around it.
sql you are generating
select * from 'employees' where last_name = 'Smith'
What sql you want
select * from employees where last_name = 'Smith'
you would have to format the string first like the example below.
query = "SELECT * from {} wherre last_name ='{}'"
cursor.execute(query.format("employees","Smith"))
using code like this does open up the possibility of SQL injection. so please bear that in mind.
query="SELECT * FROM %s WHERE name=%s",(employees,smith)
cursor.execute(query)
rows = cursor.fetchall()
Try this one. Hopefully it works for you.
What is the correct method to have the tuple (names) be available via %s in the SQL statement?
names = ('David', 'Isaac')
sql = 'SELECT * from names WHERE name IN %s'
cur.execute(sql,(names,))
The response in https://stackoverflow.com/a/28117658/5879128 works for psycopg2 but does not work in pg8000.
Thanks!
Generate the proper number of placeholders. In pg8000 the placeholder defaults to %s.
Interpolate placeholders to the query string.
Execute SQL-injection-safe query.
Like so:
sql = 'SELECT * from names WHERE name IN ({})'.format( ','.join(['%s']*len(names)) )
# results in -> 'SELECT * from names WHERE name IN (%s,%s)'
cur.execute(sql,(names,))