cursor.fechtmany(size=cursor.arraysize) in Sqlite3 - python

I want to retrieve the 100 first rows of my Sqlite3 database:
connection = sqlite3.connect('aktua.db')
cursor = connection.cursor()
print('Actual \tCliente \tHistórica')
cursor.execute("SELECT * FROM Referencias WHERE r_aktua LIKE '%K'").fetchmany(size=100)
for row in cursor:
print('%s \t%s \t%s' % row)
cursor.close()
connection.close()
My code retrieves all rows of the database (+4000).
I've read sqlite3.Cursor.fetchmany Docs and SQLite Python Tutorial.
What's wrong?

Use this to limit the sql selection:
"SELECT * FROM Referencias WHERE r_aktua LIKE '%K' LIMIT 100"
Or changue your code to:
rows = cursor.execute("SELECT * FROM Referencias WHERE r_aktua LIKE '%K'").fetchmany(size=100)
for row in rows:
print('%s \t%s \t%s' % row)

Related

Python3 - SQLITE - Shows only one row

this is my python code to get all tickets from a sqlite database, where the "IR" number is the same. When I run it and search a value, sqlite prints only one row, for the value "IR". But there are two rows in my database. This is my Database:
Database content
def seek(IR):
conn = sqlite3.connect("Test.db")
cur = conn.cursor()
sql = "SELECT IR FROM Tickets WHERE IR = ?"
cur.execute(sql, (IR))
fetch = cur.fetchall()
print("Printing IR ", IR)
print("Total rows are: ", len(fetch))
for row in fetch:
print("IR: ", row[0])
print("Stellplatz: ", row[2])
conn.close()
I solve the issue on my own. I forgot the "*" in the SQL Statment.

sqllite3 table not available even after comitting, Operational Error: no such table

I created a test db as below, which works fine in the same python script.
import sqlite3 as db
conn = db.connect('test.db')
cursor = conn.cursor()
cursor.execute("drop table if exists temps")
cursor.execute('create table temps(date text, temp int)')
cursor.execute('insert into temps values("12/1/2011",35)')
cursor.execute('insert into temps values("13/1/2011",45)')
cursor.execute('insert into temps values("14/1/2011",42)')
cursor.execute('insert into temps values("15/1/2011",39)')
cursor.execute('insert into temps values("16/1/2011",41)')
conn.commit()
conn.row_factory = db.Row
cursor.execute('select * from temps')
rows= cursor.fetchall()
for row in rows:
print ("%s %s" % (row[0], row[1]))
conn.close()
But When I access the same DB over a different script, I am able to open a connection but it shows error when I try to access the temps table.
import sqlite3 as db
conn = db.connect('test.db')
cursor = conn.cursor()
conn.row_factory = db.Row
cursor.execute("select * from temps")
rows=cursor.fetchall()
for row in rows:
print ("%s %s" % (row[0], row[1]))
Error:
cursor.execute('select * from temps')
sqlite3.OperationalError: no such table: temps
You need to supply the correct path to your database, the first script creates a database in the same folder as the one it is ran in.
For ease we will assume your first script is running in C:\DataBase, when it runs you will now see a file test.db in the DataBase folder. This file is your sqlite3 database. To access this from another python script on the same machine you would need to:
import sqlite3 as db
conn = db.connect('C:\DataBase\test.db')
cursor = conn.cursor()
conn.row_factory = db.Row
cursor.execute("select * from temps")
rows=cursor.fetchall()
for row in rows:
print ("%s %s" % (row[0], row[1]))
Otherwise as you may have noticed the second script will just create a new database file test.db in the folder it was ran from.

python mysql select return only first row of table, not all

im dealing with strage problem and this is like this:
this query should return all of my table:
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
cursor.fetchall()
for row in cursor:
print row
for loop should print all rows in cursor but it will only print the first one.
it seems cursor is filled with first row only.
is there anything that i missed here?
thanks
You need to put the output of cursor.fetchall() into a variable. Like
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
rows = cursor.fetchall()
for row in rows:
print row
You can try limit:
cursor.execute("select * from mytable limit 1")
Try
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
for row in cursor.execute("select * from mytable"):
print row
you need a dic and save the result here
dic={}
cursor.execute("select * from table")
dic['table']=cursor.fetchall()
for row in range(len(dic['table'])):
print dic['table'][row]
and if you need print any colum
print dic['table'][row]['colum']
This is not the correct way to use the .fetchall() method. Use cursor.stored_results() and then do a fetchall() on the results to perform this task, like this:
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
results = cursor.stored_results()
for result in results:
print result.fetchall()
I also had this problem. My mistake was that after inserting new row in the table I didn't commit the result. So you should add db.commit() after INSERT command.
i know its been very long time since, but i didnt find this answer anywhere else and thought it might help.
cursor.execute("SELECT top 1 * FROM my_table")

Can i store a cursor.fetchone() in a variable

Hell guys just jumped in to python and i'm having a hard time figuring this out
I have 2 queries . . query1 and query2 now how can i tell
row = cursor.fetchone() that i am refering to query1 and not query2
cursor = conn.cursor()
query1 = cursor.execute("select * FROM spam")
query2 = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()
thanks guys
Once you perform the second query, the results from the first are gone. (The return value of execute isn't useful.) The correct way to work with two queries simultaneously is to have two cursors:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2
It doesn't. The return value from cursor.execute is meaningless. Per PEP 249:
.execute(operation[,parameters])
Prepare and execute a database operation (query or
command)...
[...]
Return values are not defined.
You can't do it the way you're trying to. Do something like this instead:
cursor = conn.cursor()
cursor.execute("select * FROM spam")
results1 = cursor.fetchall()
cursor.execute("select * FROM eggs")
if results1 is not None and len(results1) > 0:
print "First row from query1: ", results1[0]
row = cursor.fetchone()
if row is not None:
print "First row from query2: ", row

How to check with python if a table is empty?

Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
print "This table is empty!"
Something like
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data
will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.

Categories