how print count table sql in python - python

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()

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.

Python sqlite loop thought all tables in database

I have 700 tables in a test.db file, and was wondering how do I loop through all these tables and return the table name if columnA value is -?
connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"')
How do I put all 700 tables in all_tables?
To continue on a theme:
import sqlite3
try:
conn = sqlite3.connect('/home/rolf/my.db')
except sqlite3.Error as e:
print('Db Not found', str(e))
db_list = []
mycursor = conn.cursor()
for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"):
db_list.append(db_name)
for x in db_list:
print "Searching",x[0]
try:
mycursor.execute('SELECT * FROM '+x[0]+' WHERE columnA" = "-"')
stats = mycursor.fetchall()
for stat in stats:
print stat, "found in ", x
except sqlite3.Error as e:
continue
conn.close()
SQLite
get all tables name:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
Cycle
for table in tables:
...
connection.execute('SELECT * FROM "table1" WHERE "columnA" = "-"')
or one SQL request UNION
sql = []
for table in tables
sql.append('(SELECT * FROM "' + table + '" WHERE "columnA" = "-";)')
' UNION '.join(sql)
You could query the sqlite_master to get all the table names within your database: SELECT name FROM sqlite_master WHERE type = 'table'
sqlite_master can be thought of as a table that contains information about your databases (metadata).
A quick but most likely inefficient way (because it will be running 700 queries with 700 separate resultsets) to get the list of table names, loop through those tables and return data where columnA = "-":
for row in connection.execute('SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name').fetchall()
for result in connection.execute('SELECT * FROM ' + row[1] + ' WHERE "columnA" = "-"').fetchall()
# do something with results
Note: Above code is untested but gives you an idea on how to approach this.

How do I get tables in postgres using psycopg2?

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()

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 do I execute SQL_CALC_FOUND_ROWS in python MySQLDB

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()

Categories