I'm using this function :
def checker(name,s)
MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"
I want to check if the table exists, how can I do it ?
I saw some examples using : XXXX.execute()
what does it mean?
Here is what I saw :
query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
(prefix, code_id, answer, station,))
if query != 1:
I tried printing MY_T to see if it returns -1 for example but it just prints "select count (*)...... "
How can I check it? Any help would be very appreciated.
or in Python using psycopg2 : cur. execute( """ SELECT COUNT(*) = 1 FROM pg_tables WHERE tablename = 'my_table'; """ ) exists = cur. fetchone()[0] print(exists) True if exists is False: # table does not exist ...
To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.
Show activity on this post. 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!"
Use the "TABLES" information schema view. http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
SELECT * FROM information_schema.tables
WHERE table_name = 'YOUR TABLE'
You can apply this view to your code by doing something like the following:
def checkTableExists(dbcon, tablename):
dbcur = dbcon.cursor()
dbcur.execute("""
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_name = '{0}'
""".format(tablename.replace('\'', '\'\'')))
if dbcur.fetchone()[0] == 1:
dbcur.close()
return True
dbcur.close()
return False
If you are using Python-MySQL (MySQLdb) -> http://mysql-python.sourceforge.net/MySQLdb.html
cursor.execute() is the method to run queries with MySQLdb, Python MySQL driver. You can pass two arguments, like:
cursor.execute(statement, parameters)
And will execute "statement" parsing "parameters" to the statement. You need to have opened a database connection and also open a cursor
I think you can use MySQL's statement: SHOW TABLES LIKE 'tablename';
stmt = "SHOW TABLES LIKE 'tableName'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
# there is a table named "tableName"
else:
# there are no tables named "tableName"
EDIT: there will other Python drivers with similar behaviour. Look for yours :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With