I am work with python. I have code like this :
def return_auth_notificatio():
shiporderid = all_Orderid
cursor.execute("select *from return_auth_notification")
email_record = cursor.fetchall()
for row in email_record:
Orderid = row[1]
Customercomment =row[4]
Amountreturn =row[5]
condition_return_auth_notificatio=(Customercomment,Amountreturn if shiporderid == Orderid else None)
assign_return_auth_notificatio=(condition_return_auth_notificatio if !Null )
return(assign_return_auth_notificatio)
data=return_auth_notificatio()
all_Customercomment=data[0]
all_Amountreurn=data[1]
I want this variable Customercomment,Amountreturn if records whose Orderid matches all_Orderid
Put the condition in the query instead of the loop.
def return_auth_notificatio():
customer_comments = []
amount_returns = []
cursor.execute("""
select Customercomment, Amountreturn
from return_auth_notification
WHERE Orderid = %s""", (all_Orderid,))
for comment, amount in cursor.fetchall():
customer_comments.append(comment)
amount_returns.append(amount)
return customer_comments, amount_returns
all_Customercomment, all_Amountreturn = return_auth_notificatio()
The placeholder %s assumes you're using MySQL. If it's SQLite use ? instead.
Related
Newby working my way through python and sql with mariadb.
Why wont this loop? It updates the first record only. Im pretty hack at this...
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
else:
result = 1
upd_data=(result,rid)
sql1 = ("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s")
cursor2.execute(sql1,upd_data)
conn.commit()
Since you are fetching multiple rows you have to store the fetched values in an array and use cursor's executemany() method instead.
✂
data= []
for x in records:
rid = (x[0])
result= int(x[1] > x[2])
data+= [(result, rid)]
cursor.executemany(UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s", data);
✂
When using mariadb python module (MariaDB Connector/Python) this is much more effective since it reduces network traffic: instead of sending n update commands in a loop (where n is the number of rows in table pumped) only one command will be send to the server.
conn = msql.connect(host=Host,port=Port, user=User, password=Password, database=database)
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
else:
result = 1
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
I want to search a mysql table for rows where the specified column has a particular value. For example, given the input string memory=2048 it will search for the rows that have "2048" as the value of memory column and it will print them.
This is code that I have tried but it print outs nothing.
input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]
mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE %s LIKE %s)"
val = (tag, desc)
mycursor.execute(sql, val)
res = mycursor.fetchall()
for x in res:
print(x)
Secondly I tried this code to see where is the problem :
input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]
mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE memory LIKE '2048')"
mycursor.execute(sql)
res = mycursor.fetchall()
for x in res:
print(x)
It gives the desired output. So my problem is when I am trying to get the column name with %s it comes as 'memory' and It couldn't finds it, since the name of the column is memory. Is there a way to get rid of the '' chars ?
confirmation of inputs
Looking at the mysql.connector's execute() documentation it appears to use %s as placeholders for bind parameters.
So your execute("SELECT * FROM comp WHERE %s LIKE %s", ("memory", "2048")) call ends up running like the following SQL:
SELECT * FROM comp WHERE 'memory' LIKE '2048'
obviously returning 0 rows.
You need to put the literal column name into the query text before invoking execute():
sql = "SELECT * FROM comp WHERE %s LIKE %s" % (tag, "%s")
# => "SELECT * FROM comp WHERE memory LIKE %s"
mycursor.execute(sql, (desc, ))
I am trying to use variables in a python function to try and retrieve attributes with mysql connector
It seems to work only when I specify the name of the attribute in the query itself
def insert(ids, added_attribute):
insert = ''
if len(ids) > 0:
#insert scpecified attributes wanted
insert += ' AND (%s = %s' %(added_attribute, ids[0])
#for loop for more than one specified specific attribute
for id_index in range(1, len(ids)):
insert += ' OR %s = %s' %(added_attribute, ids[id_index])
insert += ')'#close parenthesis on query insert
return insert
def get(name, attributes = 0, ids = []):
cursor = conn.cursor()
#insert specific ids
insert = insert(ids, "id")
query = 'SELECT %s FROM (TABLE) WHERE (name = %s%s)'
cursor.execute(query, (attributes, name, insert))
data = cursor.fetchall()
cursor.close()
return data
I keep getting null as a return value
Try this...
query = 'SELECT {} FROM (TABLE) WHERE (name = {}{})'
cursor.execute(query.format(attributes, name, insert))
{} is replacing %s here and to call the variables you just need to add .format() with the vars you want inserted in order.
I would like to know, how I want to write some code, which gives me the index of element found in database.
I have function like this:
def get_teachers_names(name, lastname):
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
select_query = "SELECT id FROM lecturers WHERE name = %s AND lastname = %s"
record_to_find = (name, lastname)
cur.execute(select_query, record_to_find)
records = list(cur)
conn.commit()
cur.close()
return records
except (Exception, psycopg2.DatabaseError) as error:
print(error)
When I do something like:
index = database.get_teachers_names('Name1', 'Surname1')
I get index I want. But when I have a lists:
names = ('Name1', 'Name2')
surnames = ('Surname1', 'Surname2')
And I try to do the same with:
index = database.get_teachers_names(names[0], surnames[0]
I get [] as result. I also tried:
index = database.get_teachers_names(''.join(names[0], ''.join(surnames[0]))
But it also didn't work. Any suggestions?
It works when you pass a simple strings as they will populate the query string correctly:
index = database.get_teachers_names('Name1', 'Surname1')
However when you pass a list it won't be parsed correctly as a string in:
"SELECT id FROM lecturers WHERE name = %s AND lastname = %s"
I think the best approach for you is to loop over the list and execute this for each entry:
cur.execute(select_query, record_to_find)
You can then append the results to a the records list.
Can someone tell me why the code below is throwing errors. Its meant to look at the current id and if its less the max to descend to the next row in the database and print it.
def loadData(self):
connection = sqlite3.connect('films.db')
c = connection.cursor()
maxid_before = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)")
last_row = maxid_before.fetchone()[0]
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < (last_row) ORDER BY ID DESC LIMIT 1;").fetchone()
print(maxid_after)
UPDATE
This is the function that calls loadData.What silly mistake have i done this time.You can ignore the first 5 lines or so.
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.edit_btn.clicked.connect(self.Retrieve)
self.edit_save_btn.clicked.connect(self.insertData)
last_id = 0
if not last_id:
connection = sqlite3.connect('films.db')
c = connection.cursor()
result = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)")
last_id = result.fetchone()[0]
self.edit_load_btn.clicked.connect(self.loadData)
And this is the loadData function
def loadData(self, last_id):
connection = sqlite3.connect('films.db')
c = connection.cursor()
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_id,)).fetchone()
print(maxid_after)
return maxid_after
Try this -
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_row,)).fetchone()
In your code last_row is a variable not column name. So, you should put the value of last_row in the query.
If you put last_row in the query like you did, sqlite will treat last_row as a column name and try to execute the query like that. As it fails to find any column by that name, it throws the error.
If you want to run this function on a button click and return one by one row in descending order in every button click, then your function should be like this -
def loadData(self):
connection = sqlite3.connect('films.db')
c = connection.cursor()
result = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_id,)).fetchone()
if result:
self.last_id = result[0]
connection.close()
And the function that calls loadData() should be like -
# This is the code that calls loadData()
# This is __init__
result = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)").fetchone()
if result:
self.last_id = result[0]
...
# On button click
# Call loadData