Iterate over databse array flask [duplicate] - python

This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 2 years ago.
I am relatively new to flask and I am having some issues with displaying my database as a html table. I don't know if this might be a stupid question, but I don't know how to get the values from this array.
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT CardNo, CardName, CardExpDate, CardSecretCode FROM carddetails WHERE UID=%s", (session['id'],))
rows = cursor.fetchall()# data from database
for row in rows:
print(row)
for i in row:
print(i)
{'CardNo': '4561441635108144', 'CardName': 'Zachery Williamson', 'CardExpDate': '12-25', 'CardSecretCode': '219'}
CardNo
CardName
CardExpDate
CardSecretCode
{'CardNo': '4590618204792680', 'CardName': 'SAM LETTUCE', 'CardExpDate': '03-23', 'CardSecretCode': '440'}
CardNo
CardName
CardExpDate
CardSecretCode
I want to get the values next to the colon for each of them, but I don't know why it only returns the first bit which is useless for my purpose. My idea is implementing those values in a html table, but I am struggling with it. By the way, tha card information displayed above is completely random.

cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT CardNo, CardName, CardExpDate, CardSecretCode FROM carddetails WHERE UID=%s", (session['id'],))
rows = cursor.fetchall()# data from database
for row in rows:
print(row)
for i in row:
print(i, row[i])
With for i in row, you iterate over a dictionary and i is a key for each iteration. To get the associated value, you have to get it like for all dictionaries in Python row[i].

Related

How to only get second row data from Sqlite? [duplicate]

This question already has answers here:
Sqlite LIMIT / OFFSET query
(3 answers)
Closed 12 months ago.
I am new to Python and I recently stuck in getting value from Sqlite. What I want is getting value only in second row of the table. This is the table data picture. And I have tried this but not working:
con = sqlite3.connect(database=r'ims.db')
cur = con.cursor()
for l in range(1,8):
cur.execute(f"Select occolor{l} from ordercart limit 2")
row = cur.fetchall()
print(row)
This will bring both first and second row value. But what I want are only the second row value. Anyone help with this pls?
fetchall returns a reference to a list. Your query will return at most 2 rows. Therefore:
if (row := cur.fetchall()):
print(row[-1])
else:
print('Not found')
Doing it like this allows for the results being either empty or containing just one row

sqlite3: How to use SELECT + WHERE to search a random row? [duplicate]

This question already has answers here:
SQLite - ORDER BY RAND()
(5 answers)
Closed 5 years ago.
Eg. In the Table1 there is a column ColName, some of the items in ColName are "Mike".
The code to search one of the them:
searchString = " SELECT * FROM Table1 WHERE ColName = 'Mike' "
cur.execute(searchString).fetchone()
The Problem: The code above allways gives me the first row, where "Mike" in ColName appears.
I actually want, by everytime running the sqlite code, to get a random search result from the column ColName, whose value is "Mike". How could I change the code?
Thanks for the help!
If you want a random value, then you need to iterate over cur.execute(searchString) for some random amount, then extract the column(s).
fetchone() always returns the top result
The alternative includes trying to randomly sort the query results in SQL

sql output in treeview columns using tkinter module in python

i am trying to output 2 different returns from sql queries in to the respective columns in a treeview widget using tkinter module in python 3.4 When i run command defined below the first column prints all the entries correctly but the name column prints the name of the first result in all rows instead of name per respective row. Any ideas on what im doing wrong?
def refreshtrade():
for i in treeview.get_children():
treeview.delete(i)
#order number
refreshtradein = conn.cursor()
refreshtradein.execute("SELECT increment_id FROM mg_ikantam_buyback_order")
#first name
names =conn.cursor()
names.execute("SELECT customer_firstname FROM mg_ikantam_buyback_order")# WHERE increment_id = 'buyback-%s'" %(tradeinentryfield.get() ))
for n in names:
for r in refreshtradein:
treeview.insert('',0,r,text = r, values=(n,'Mercedes', 'Purchased', '8-34-15'))
refreshtradein.close()
conn.close()
Why are you using two different cursors and consequently two nested for loops? Are you aware how nested for loops are evaluated?
querycursor = conn.cursor()
querycursor.execute(SELECT increment_id, customer_firstname FROM mg_ikantam_buyback_order)
for row in querycursor:
print(row[0])
print(row[1])
Oh and regarding your where clause. Don't ever do parameter substitution like that. It is great security risk
See here how to do it correctly

Elegant way to update multiple values for Sqlite3 Python

I have an Sqlite3 database called MYTABLE like this:
My objective is to update the values of COUNT column by simply adding the existing value with the new value.
There will be two inputs that I will recieve:
Firstly, a list of IDs that I need to update for COUNT column.
For example: ['1','3','2','5']
And Secondly, the number of count to be added to the every IDs in
the list above.
So far, the best I can come up with is:
#my input1, the list of IDs that need updating
id_list = ['1','2','5','3']
#my input2, the value to be added to the existing count value
new_count = 3
#empty list to store the original count values before updating
original_counts = []
#iterate through the input1 and retrieve the original count values
for item in id_list :
cursor = conn.execute("SELECT COUNT from MYTABLE where ID=?",[item])
for row in cursor:
original_counts.append(row[0])
#iterate through the input1 and update the count values
for i in range(len(id_list )):
conn.execute("UPDATE MYTABLE set COUNT = ? where ID=?",[original_counts[i]+new_count ,mylist[i])
Is there better/more elegent and more efficient way to achieve what I want?
UPDATE 1:
I have tried this based on N Reed's answer(not exactly the same) like this and it worked!
for item in mylist:
conn.execute("UPDATE MYTABLE set VAL=VAL+? where ID=?",[new_count,item])
Take Away for me is we can update a value in sqlite3 based on it's current value(which I didn't know)
You want to create a query that looks like this:
UPDATE MYTABLE set COUNT = COUNT + 5 where ID in (1, 2, 3, 4)
I don't know python that well, but you probably want code in python something like:
conn.execute("UPDATE MYTABLE set COUNT = COUNT + ? where ID in (?)", new_count , ",".join(mylist))
Keep in mind there is a limit to the number of items you can have in the Id list with sqllite (I think it is something like 1000)
Also be very careful about sql injection when you are creating queries this way. You probably will want to make sure that all the items in mylist have already been escaped somewhere else.
I also recommend against having a column called 'count' as it is a keyword in sql.

Obtaining data from PostgreSQL as Dictionary

I have a database table with multiple fields which I am querying and pulling out all data which meets certain parameters. I am using psycopg2 for python with the following syntax:
cur.execute("SELECT * FROM failed_inserts where insertid='%s' AND site_failure=True"%import_id)
failed_sites= cur.fetchall()
This returns the correct values as a list with the data's integrity and order maintained. However I want to query the list returned somewhere else in my application and I only have this list of values, i.e. it is not a dictionary with the fields as the keys for these values. Rather than having to do
desiredValue = failed_sites[13] //where 13 is an arbitrary number of the index for desiredValue
I want to be able to query by the field name like:
desiredValue = failed_sites[fieldName] //where fieldName is the name of the field I am looking for
Is there a simple way and efficient way to do this?
Thank you!
cursor.description will give your the column information (http://www.python.org/dev/peps/pep-0249/#cursor-objects). You can get the column names from it and use them to create a dictionary.
cursor.execute('SELECT ...')
columns = []
for column in cursor.description:
columns.append(column[0].lower())
failed_sites = {}
for row in cursor:
for i in range(len(row)):
failed_sites[columns[i]] = row[i]
if isinstance(row[i], basestring):
failed_sites[columns[i]] = row[i].strip()
The "Dictionary-like cursor", part of psycopg2.extras, seems what you're looking for.

Categories

Resources