converting to string from sqlite tuple - python

When I retrieve data from my database, it is returned in the following format however I need it simply as just the text on its own:
[(u'milk',)]
[(7,)]
i have tried converting it into a string etc so that I could use a for loop to iterate through it and pop off the unneeded characters but nothing has worked
Here is my code:
def retShopping(db):
item = []
quan = []
with sqlite3.connect(db) as db:
cursor = db.cursor()
cursor.execute('''SELECT quantity FROM Shopping''')
hold = str(cursor.fetchall())
quan.append(hold)
cursor.execute('''SELECT item FROM Shopping''')
hold2 = str(cursor.fetchall())
item.append(hold2)
print(item[0])
print(quan[0])
I am hoping to be able to just end up with the strings'milk' and '7' so that I am able to use them in print statements.

try this:
def retShopping(db):
with sqlite3.connect(db) as db:
cursor = db.cursor()
cursor.execute('''SELECT quantity FROM Shopping''')
hold = cursor.fetchall()
print(hold[0][0])
cursor.execute('''SELECT item FROM Shopping''')
hold2 = cursor.fetchall()
print(hold2[0][0])

Related

show only one data in python query

I write to see how I can get only one data to show by a print when I make a query in python, when I do the query it should only give me a number but I cannot show or access it.
def run_query(self, query, parameters = ()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
conn.commit()
return result
def get_horarios(self):
query = 'SELECT hora FROM horarios where horario=1'
db_rows = self.run_query(query)
print(db_rows)
To show the first row in the results of the query:
print(db_rows.fetchone())
To show all of the results of the query:
print(db_rows.fetchall())
or
for row in db_rows.fetchall():
print(row)
The query always return a list. To access the first item, you can do:
print(db_rows[0])

Getting TypeError: argument 1 must be str, not tuple when searching in DB

Could you please help a noobie.
I'm getting this error when trying to search and display data from database in my GUI.
'''
search_box = Entry(search_products)
search_box_get = search_box.get()
search_box_get = str(search_box_get)
def search_product_name():
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
# selects everything from the table called Products
sql = "SELECT * FROM Products WHERE product_name=?", search_box_get
all_rows = cursor.execute(sql)
for record in table.get_children():
table.delete(record)
for i in all_rows:
table.insert('', 'end', values=i)
connection.commit()
'''
That's the error I'm getting
all_rows = cursor.execute(sql)
TypeError: argument 1 must be str, not tuple
sql is a tuple but cursor.execute() requires a SQL string and a tuple/list arguments.
Also you should get the content of search_box inside search_product_name():
def search_product_name():
search_box_get = search_box.get()
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
sql = "SELECT * FROM products WHERE product_name = ?"
all_rows = cursor.execute(sql, [search_box_get])
...

print the most common value from sql

I have a list of words in an SQLite database and I want to get the most common value and save it in a variable.I am using python3
here is how I got my most common value.
SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1;
May be something like this?
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('yourdb')
cur = conn.cursor()
cur.execute('''SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1''')
rows = cur.fetchall()
    for row in rows:
        x = row[0]
y = row[1]
print(x,y)

Index out of range while executing results from db

I'm having a problem while trying to simply execute data from rows from db (sqlite3). The DB input has 4 fields, therefore once entered they're being saved. But here's my problem, where I execute all of the 4 rows, if one of the fields was not filled I get an error.
That's the database execute code:
def ids(self):
con = lite.connect('foo.db')
with con:
cur = con.cursor()
cur.execute("SELECT Id FROM foo")
while True:
ids = cur.fetchall()
if ids == None:
continue
return ids
And since there are 4 rows, my output code:
print ''.join(ids[0]) + ',' + ''.join(ids[1]) + ',' + ''.join(ids[2])
+ ',' + ''.join(ids[3])
so my question is how to make an exception when there's no existing row to not show anything and just leave the ones that actually exist? I tried doing if ids[0] is not None: #do something but that would make my code really slow and it's non-pythonic way I guess. Is there any better way to make that work? Any help will be appreciated.
You don't seem to have 4 rows. Make it generic and just join an arbitrary number of rows:
ids = someobject.ids()
print ','.join(''.join(row) for row in ids)
You can simplify your database query, there is no need to 'poll' the query:
def ids(self):
with lite.connect('foo.db') as con:
cur = con.cursor()
cur.execute("SELECT Id FROM foo")
return cur.fetchall()
You could also just loop directly over the cursor, the database will handle buffering as you fetch:
def ids(self):
with lite.connect('foo.db') as con:
cur = con.cursor()
cur.execute("SELECT Id FROM foo")
return cur # just the cursor, no fetching
ids = someobject.ids()
# this'll loop over the cursor, which yields rows as required
print ','.join(''.join(row) for row in ids)

Python MySQLDB: Get the result of fetchall in a list

I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries.
For example,
cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor
query = "Select id from bs"
cursor.execute(query)
row = cursor.fetchall()
Now, the problem is the resultant row is either ((123,),(234,)) or ({'id':123}, {'id':234})
What I am looking for is (123,234) or [123,234]. Be best if I can save on parsing the resulset.
And what about list comprehensions? If result is ((123,), (234,), (345,)):
>>> row = [item[0] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
If result is ({'id': 123}, {'id': 234}, {'id': 345}):
>>> row = [item['id'] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found here:
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM Writers LIMIT 4")
rows = cur.fetchall()
for row in rows:
print row["Id"], row["Name"]
This old Q comes up on Google while searching for flattening db queries, so here are more suggestions...
Consider a fast list-flattening iterator.
Others answers use fetchall() which first loads all rows in memory, then iterates over that to make a new list. Could be inefficient. Could combine with MySQL so-called server side cursor:
# assume mysql on localhost with db test and table bs
import itertools
import MySQLdb
import MySQLdb.cursors
conn = MySQLdb.connect(host='localhost',db='test',
cursorclass=MySQLdb.cursors.SSCursor )
cursor = conn.cursor()
# insert a bunch of rows
cursor.executemany('INSERT INTO bs (id) VALUES (%s)',zip(range(1,10000)) )
conn.commit()
# retrieve and listify
cursor.execute("select id from bs")
list_of_ids = list(itertools.chain.from_iterable(cursor))
len(list_of_ids)
#9999
conn.close()
But the question is also tagged Django, which has a nice single field query flattener
class Bs(models.Model):
id_field = models.IntegerField()
list_of_ids = Bs.objects.values_list('id_field', flat=True)
Make your cursor object in this manner:
db = MySQLdb.connect("IP", "user", "password", "dbname")
cursor = db.cursor(MySQLdb.cursors.DictCursor)
Then when you perform cursor.fetchall() on a query, a tuple of dictionaries will be obtained, which you can later convert to a list.
data = cursor.fetchall()
data = list(data)
list= [list[0] for list in cursor.fetchall()]
this will render results in one list like - list = [122,45,55,44...]
If there is only one field, i can use this to make a list from database:
def getFieldAsList():
kursor.execute("Select id from bs")
id_data = kursor.fetchall()
id_list = []
for index in range(len(id_data)):
id_list.append(id_data[index][0])
return id_list
cursor.execute("""Select * From bs WHERE (id = %s)""",(id))
cursor.fetchall()

Categories