Convert MySQL query to Python - python

I am trying to write a SELECT query with a WHERE condition and ORDER BY.
I have the query in MySQL and would like to convert it to Python.
This is my Mysql-Query:
SELECT StoreId
, ProductCode
, TotalQuantity
FROM storeinvoicedetails
WHERE StoreId=1
ORDER BY ProductCode
This is what I tried in Python:
sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d'" % (1) \
"ORDER BY '%s' '%s'" % ('ProductCode','ASC')

query = """SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails WHERE StoreId={0} ORDER BY ProductCode ASC""".format(store_id)

> sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d' \
ORDER BY ProductCode ASC" % id
This should work.

STOREID = 1
# make sure you add the last space for every line, otherwise it will look like 'TotalQuantityFROM' causing an error
myQuery = "SELECT StoreId,ProductCode,TotalQuantity " +
"FROM storeinvoicedetails " +
"WHERE StoreId=" + str(STOREID) + " "
"ORDER BY ProductCode"

Related

Python MYSQL dynamically select fields from one table where they exist in another

I have a table task_field where I store field headers as records that exist in another table product_wca as follows:
Now I have a query pulling data from the product_wca table, however I would like to select fields from this table that are in the table above as per 'name' field.
I'm not sure if this is possible to do in MYSQL alone as I cannot join on anything but hope it's possible with python, please see my failed attempt at this below where I tried to add a python for loop inside the mysql select statement:
Get list of fields from first table
mycursor = mydb.cursor()
mycursor.execute("SELECT name" \
" FROM `wfi-workflow`.task_field " \
"where " \
" taskid = 50 " \
" and model = 'wca'")
My failed attempt to show select fields from another table where available in table above:
newcursor = mydb.cursor()
mycursor.execute("select distinct portfolio.id," \
"portfolio.secid," \
for x in mycursor:
for i in x:
"Wca.'+i+', " \
"portfolio.code " \
"from portfolio_identifier portfolio " \
"left join product_wca WCA on portfolio.secid = WCA.secid " \
"where portfolio.account_id = 319 limit 1")
Is it possible to do what I'm attempting or another work around to only select fields from one table where they exist in another?
You can't put a for loop in the middle of an expression. Use the str.join() method to create a string containing the concatenated results.
mycursor = mydb.cursor()
mycursor.execute("""SELECT name
FROM `wfi-workflow`.task_field
where
taskid = 50
and model = 'wca'""")
names = ",".join("wca."+row[0] for row in mycursor)
mycursor.execute("""select distinct portfolio.id,
portfolio.secid,""" +str(names)+ """, portfolio.code
from portfolio_identifier portfolio
left join product_wca WCA on portfolio.secid = WCA.secid
where portfolio.account_id = 319 limit 1""")

Python Mysql and dynamically defining fields

Is it possible to dynamically define the ORDER BY field through parameters? Through a relentless search, I've come up with that you can't.
So I thought I would ask if you can? Or if there is a work around to do it?
Example:
sql = "SELECT `xyz` FROM `checkins` WHERE `name`=%s AND `timestamp` >=%s AND `timestamp` < %s ORDER BY `xyz` DESC LIMIT 1"
query.execute(sql, (name, start, end))
works
sql = "SELECT `xyz` FROM `checkins` WHERE `name`=%s AND `timestamp` >=%s AND `timestamp` < %s ORDER BY `%s` DESC LIMIT 1"
query.execute(sql, (name, start, end, field))
does not work
The aim is to make the ORDER BY field dynamically defined (with the field variable), however when I do try to define dynamically, it keeps coming back with unknown field or disregarding the field because it's changing it to 'defined_field' with quotes
I have tried removing the ` from the ORDER BY as well
I am biased against %s for something like this. You could try:
name = 'kbball'
start = '2017'
end = '2018'
field = 'field'
sql = "SELECT `xyz` FROM `checkins` WHERE `name`= " + name + " AND `timestamp` >= " + start + " AND `timestamp` < " + end + " ORDER BY `"+ field + "` DESC LIMIT 1"
print(sql)
#output SELECT `xyz` FROM `checkins` WHERE `name`= kbball AND `timestamp` >= 2017 AND `timestamp` < 2018 ORDER BY `field` DESC LIMIT 1

Using (Select * from a table ) to insert data into a table

I have bottom MySql query (sql1).
sq1 = 'select course_id, creator_id, max(course_num) + 1, recordid
' from Courses where recordid in' \
' (' + ','.join(map(str, RecordMatch1)) + ') group by recordid'
cursor.execute(sql1)
BTW, RecordMatch1 is an object that has matching data from other previous queries.
I am trying to see if this is possible; (select * from sql1) portion.
sql2 = ' insert into Courses (course_id, creator_id, course_num, record_id) '\
' Values ( select * from sql1)'
cursor.execute(sql2)
Or do I have to express everything rather than using (Select * )?
What is best practice?
You can do this, but you should specify columns in case of schema changes.
Just need to confirm you are trying to run a select query and insert its output to a insert query. If that is the case this appears to be good.
yes, you can but you should do something like
sql = "SELECT course_id, creator_id, course_num, record_id FROM Courses"
all = cursor.fetchall()
for i in range(len(all))
sql1 = "INSERT INTO Courses (course_id, creator_id, course_num, record_id) VALUES (%s, %s, %s, %s)"
cursor.execute(sql1, (all[i]['Key'], all[i]['Key2'], all[i]['Key3'], all[i]['Key3']))
you can change the select like you want, remember that return a dictionary so take care about the keys, add print(all) to see what happen with the select and see the keys of each column

Trouble with SQL in python

I have this Python code:
def get_employees(conditions, fields):
cursor.execute("SELECT employeeID FROM employees WHERE name=%s, budget=%s,
%year=%s,(some of conditions))
Is there any way to get employeeIDs if I set in conditions not all parameters, etc. only name and year?
If conditions were a dictionary, you could construct a query string:
def get_employees(conditions):
query = 'select employeeid from employees'
if conditions:
query += ' where ' + ' and '.join(key + ' = %s' for key in conditions.keys())
cursor.execute(query, conditions.values())
(I should note that here I am assuming that conditions does not have user-supplied keys. If there are user-supplied keys, this is definitely vulnerable to SQL injection.)
usually it is done via dynamic sql building, like this:
sql = "SELECT employeeID FROM employees WHERE 1=1";
if condition has name
sql += " and name='" .escape(name) . "'"
if condition has somefield
sql += " and somefield='" .escape(somefield) . "'"
etc
execute final sql

In Django cursor.execute("select ..") randomly returns None

I am running Django + MySql on OpenShift server and have this problem.
Code:
from django.db import connection
...
cursor = connection.cursor()
somedate = calculateSomeDate()
query = "SELECT id FROM levelbuffer WHERE START > '%s' ORDER BY START ASC LIMIT 1" % somedate
print "First select: " + query
cursor.execute(query)
sql_result = cursor.fetchone()
if not sql_result == None:
gameId = int(sql_result[0])
cursor.fetchall() #To clear anything left behind (this wasn't here before, but no changes appeared after adding)
query = "SELECT gamescores.skore, users.name FROM gamescores JOIN users ON gamescores.userId = users.id where gamescores.gameId = " + str(gameId) + " ORDER BY skore ASC"
cursor.execute(query);
#cursor.execute("SELECT gamescores.skore, users.name FROM gamescores JOIN users ON gamescores.userId = users.id where gamescores.gameId = %s ORDER BY skore ASC", (gameId))
print "Second select " + query
row = cursor.fetchone()
The weird thing is, that the row is sometimes None and sometimes it contains wanted values. I cant figure out, what i am missing. The first query works fine every time.
When I try to perform the second query printed in log on phpmyadmin - works always fine.

Categories