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' })
Related
I am trying different ways to work out on Wildcard in Python for my SQL Query, Could anyone please help me in my syntax:
I need Query like ,
SELECT Title from Task where Title like '%abc%' -- SQL
to be written in Python
TRY 1:
sql = '''
(""" SELECT TITLE FROM TASK
WHERE TITLE LIKE %s""", ('%' +?+ '%',))
'''
cursor.execute(sql, id)
data = cursor.fetchone()
TRY 2:
sql = '''
(""" SELECT TITLE FROM TASK
WHERE TITLE LIKE '%%%?%%'
'''
cursor.execute(sql, id)
data = cursor.fetchone()
ANy help on my syntax please.
I think something like this should work
sql = '''
(""" SELECT TITLE FROM TASK
WHERE TITLE LIKE '{}'
'''
sql.format(id)
cursor.execute(sql)
data = cursor.fetchone()
Here is a simple solution:
wildcard = 'example'
sql = f"""
SELECT TITLE FROM TASK
WHERE TITLE LIKE '{wildcard}'
"""
cursor.execute(sql)
data = cursor.fetchone()
This should simply replace the {wildcard} with whatever you decide in the wildcard = "?" part.
You can parse it like this :
wildcar_str = '%abc%'
sql = "SELECT TITLE FROM TASK WHERE TITLE LIKE '%s' " %wildcar_str
I have a database with some records that have a date field of "05221999". I am trying to do a SQL query from the input of the user based on just the month and year. In this case I am interested in all the records with the month of 05 and the year of 1999.
Unfortunately, I can't get the Python/SQL syntax correct. Here is my code so far:
def submitact(self):
date = self.md.get()
month = date[0:2]
year = date[2:7]
db = pymysql.connect("localhost", "username", "password", "database")
cursor = db.cursor()
cursor.execute("SELECT * FROM `table` WHERE `Code` = 'RM' AND `Date` LIKE %s'_'%s", (month, year))
results = cursor.fetchall()
print(results)
cursor.close()
db.close()
I've done several variations on the SELECT statement and they either return errors or nothing.
Thanks!
In the code snippet below, I used f-string style to format the query string
[...]
query = f"SELECT * FROM `table` WHERE `Code` = 'RM' AND LEFT(`Date`, 2) = '{month}' AND RIGHT(`Date`, 4) = '{year}'"
cursor.execute(query)
[...]
try with this:
query = "SELECT * 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%{0}_{1}'".format(month, year)
cursor.execute(query)
In this way, 'query' variable value will be:
"SELECT * FROM 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%05_1999'"
For more information about string formatting, let's have a look to Python String Formatting Best Practices - Real Python
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 am working with a SQL Database on Python. After making the connection, I want to use the output of one query in another query.
Example: query1 gives me a list of all tables in a schema. I want to use each table name from query1 in my query2.
query2 = "SELECT TOP 200 * FROM db.schema.table ORDER BY ID"
I want to use this query for each of the table in the output of query1.
Can someone help me with the Python code for it?
Here is a working example on how to do what you are looking to do. I didn't look up the schemes for the tablelist, but you can simply substitute the SQL code to do so. I just 'faked it' by unioning a statement of 2 tables. There are plenty of other answer on that SQL code and I don't want to clutter this answer:
How do I get list of all tables in a database using TSQL?
It looks like the key part you may have been missing was the join step to build the second SQL statement. This should be enough of a starting point to craft exactly what you are looking for.
import pypyodbc
def main():
table_list = get_table_list()
for table in table_list:
print_table(table)
def print_table(table):
thesql = " ".join(["SELECT TOP 10 businessentityid FROM", table])
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
print (row["businessentityid"])
cursor.close()
connection.close()
def get_table_list():
table_list = []
thesql = ("""
SELECT 'Sales.SalesPerson' AS thetable
UNION
SELECT 'Person.BusinessEntity' thetable
""")
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
table_list.append(row["thetable"])
cursor.close()
connection.close()
return table_list
def get_connection():
'''setup connection depending on which db we are going to write to in which environment'''
connection = pypyodbc.connect(
"Driver={SQL Server};"
"Server=YOURSERVER;"
"Database=AdventureWorks2014;"
"Trusted_Connection=yes"
)
return connection
main ()
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.