cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5")
rows = cursor.fetchall()
...
total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason.
Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky.
Seems to work here by fetching the result for the second cursor:
cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5")
rows = cursor.fetchall()
cursor.execute("SELECT FOUND_ROWS()")
(total_rows,) = cursor.fetchone()
Related
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)
im trying to print count table in python, im write this code:
count = cur.execute("SELECT COUNT(*) FROM %s;" str(table))
print count
all print results is 1, (think 1 = true), how i can print the real result of my sql command ?
thanks
You must fetch the result:
cursor = db.cursor()
count = cursor.execute("SELECT COUNT(*) FROM " + str(table))
db.commit()
print cursor.fetchone()[0]
cursor.close()
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 someone please explain how I can get the tables in the current database?
I am using postgresql-8.4 psycopg2.
This did the trick for me:
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
pg_class stores all the required information.
executing the below query will return user defined tables as a tuple in a list
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
print cursor.fetchall()
output:
[('table1',), ('table2',), ('table3',)]
The question is about using python's psycopg2 to do things with postgres. Here are two handy functions:
def table_exists(con, table_str):
exists = False
try:
cur = con.cursor()
cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')")
exists = cur.fetchone()[0]
print exists
cur.close()
except psycopg2.Error as e:
print e
return exists
def get_table_col_names(con, table_str):
col_names = []
try:
cur = con.cursor()
cur.execute("select * from " + table_str + " LIMIT 0")
for desc in cur.description:
col_names.append(desc[0])
cur.close()
except psycopg2.Error as e:
print e
return col_names
Here's a Python3 snippet that includes connect() parameters as well as generate a Python list() for output:
conn = psycopg2.connect(host='localhost', dbname='mySchema',
user='myUserName', password='myPassword')
cursor = conn.cursor()
cursor.execute("""SELECT relname FROM pg_class WHERE relkind='r'
AND relname !~ '^(pg_|sql_)';""") # "rel" is short for relation.
tables = [i[0] for i in cursor.fetchall()] # A list() of tables.
Although it has been answered by Kalu, but the query mentioned returns tables + views from postgres database. If you need only tables and not views then you can include table_type in your query like-
s = "SELECT"
s += " table_schema"
s += ", table_name"
s += " FROM information_schema.tables"
s += " WHERE"
s += " ("
s += " table_schema = '"+SCHEMA+"'"
s += " AND table_type = 'BASE TABLE'"
s += " )"
s += " ORDER BY table_schema, table_name;"
db_cursor.execute(s)
list_tables = db_cursor.fetchall()
you can use this code for python 3
import psycopg2
conn=psycopg2.connect(database="your_database",user="postgres", password="",
host="127.0.0.1", port="5432")
cur = conn.cursor()
cur.execute("select * from your_table")
rows = cur.fetchall()
conn.close()
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