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.
Related
I have a SQL-file (SQLite format 3) that I can query with the DB Browser for SQLite (Windows). Whenever I use Python to access the db I get a Null result.
import sqlite3
conn = sqlite3.connect('C:/tmp/test.sql')
cursor = conn.cursor()
conn.execute('select count(*) from Player')
print("result is:", cursor.fetchone()) # result is: None
Every Select statement leads to "result is: None".
Any ideas?
Bart.
import sqlite3
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
cursor.execute("select val from table_name where x = 'something';")
result = cursor.fetchone()
# directly returning result also gives null
if result:
return result[0] # tuple returned in result
cursor.close()
connection.close()
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.
Expected Output:
('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
Script:
import psycopg2
# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()
sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print('Counts:',result)
conn.close()
Current output:
[root#pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
Any help is appreciated.
Thanks!
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:
a table name cannot be a parameter in SQL
the input only comes from the program itself and is fully mastered
Possible code:
sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']
for t in tables:
cursor.execute(sql.format(t))
result = cursor.fetchall()
print("('", t, "':,", result, ")")
I believe something as below, Unable to test code because of certificate issue.
sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
for name, count in cursor:
print ("")
Or
sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print(result)
I am working with a SQL Database on Python. After making the connection, I want to use the output of one query in another query.
Example: query1 gives me a list of all tables in a schema. I want to use each table name from query1 in my query2.
query2 = "SELECT TOP 200 * FROM db.schema.table ORDER BY ID"
I want to use this query for each of the table in the output of query1.
Can someone help me with the Python code for it?
Here is a working example on how to do what you are looking to do. I didn't look up the schemes for the tablelist, but you can simply substitute the SQL code to do so. I just 'faked it' by unioning a statement of 2 tables. There are plenty of other answer on that SQL code and I don't want to clutter this answer:
How do I get list of all tables in a database using TSQL?
It looks like the key part you may have been missing was the join step to build the second SQL statement. This should be enough of a starting point to craft exactly what you are looking for.
import pypyodbc
def main():
table_list = get_table_list()
for table in table_list:
print_table(table)
def print_table(table):
thesql = " ".join(["SELECT TOP 10 businessentityid FROM", table])
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
print (row["businessentityid"])
cursor.close()
connection.close()
def get_table_list():
table_list = []
thesql = ("""
SELECT 'Sales.SalesPerson' AS thetable
UNION
SELECT 'Person.BusinessEntity' thetable
""")
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
table_list.append(row["thetable"])
cursor.close()
connection.close()
return table_list
def get_connection():
'''setup connection depending on which db we are going to write to in which environment'''
connection = pypyodbc.connect(
"Driver={SQL Server};"
"Server=YOURSERVER;"
"Database=AdventureWorks2014;"
"Trusted_Connection=yes"
)
return connection
main ()
I want to delete some rows from almost 500 tables in mysql database using python.
I know that the query should be something like this:
DELETE FROM (table name)
[WHERE conditions] [ORDER BY ...] [LIMIT rows]
but I am not sure what should I use for the table name when I looping over the tables!
here is my loop
from mysql.connector import (connection)
# call databasecnx = connection.MySQLConnection(user='user', password='PW',host='127.0.0.1', database= 'database')
cursor = cnx.cursor()
cursor.execute("SHOW TABLES LIKE 'options_20%'")
table_names = [tables for (tables, ) in cursor]
for t in table_names:
cursor.execute("Delete table-refs WHERE Expiration = Datadate AND UnderlyingSymbol = 'SPY'")
cnx.commit()
I got an error:
You have an error in your SQL syntax; check the manual that...etc
Test with this.... You did'nt put from on your query statement.
for table in table_names:
cursor.execute("DELETE FROM"+ table +"WHERE Expiration = Datadate AND UnderlyingSymbol = 'SPY'")
I am trying something like:
import pyodbc
cnxn = pyodbc.connect(driver ='{SQL Server}' ,server ='host-MOBL\instance',database ='dbname', trusted_connection = 'yes' )
cursor = cnxn.cursor()
cursor.execute("""SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'TableName'""")
def checkTableExists(cnxn, TableName):
cursor = cnxn.cursor()
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.tables
WHERE TABLE_NAME = '{0}'
""".format(TableName.replace('\'', '\'\'')))
if cursor.fetchone()[0] == 1:
cursor.close()
return True
cursor.close()
return False
if checkTableExists == True:
print ("already")
elif checkTableExists == False:
print ("No")
But there is nothing happen, can anyone help me on this?
I am using Micrsoft SQL Server Management Studio 2014 Express version.
The code will be run in Python.
Thank you
Use the built-in Cursor.tables method for this check - following code sample assumes connection and cursor are instantiated
if cursor.tables(table='TableName', tableType='TABLE').fetchone():
print("exists")
else:
print("doesn't exist")
Note this isn't functionally different from querying INFORMATION_SCHEMA.TABLES, but allows code portability with different database platforms (and IMO improves readability).
Using SQL Server Native Client 11.0 and SQL Server 2014, calling Cursor.tables just executes the sp_tables system stored procedure.
Here's a simple example:
import pyodbc
conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=yourserver.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_password;TDS_Version=7.2;')
cursor = conn.cursor()
cursor.execute("""
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'your_table_name')
BEGIN
SELECT 'Your table exists.' AS result
END
""")
rows = cursor.fetchall()
for row in rows:
print(row.result)
That prints "Table Exists" for me. You should be able to modify it to your needs.