I’m using this function :
JavaScript
x
3
1
def checker(name,s)
2
MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"
3
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:
JavaScript
1
4
1
query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
2
(prefix, code_id, answer, station,))
3
if query != 1:
4
I tried printing MY_T to see if it returns -1 for example but it just prints "select count (*)...... "
How can I check it?
Advertisement
Answer
Use the “TABLES” information schema view. http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
JavaScript
1
3
1
SELECT * FROM information_schema.tables
2
WHERE table_name = 'YOUR TABLE'
3
You can apply this view to your code by doing something like the following:
JavaScript
1
14
14
1
def checkTableExists(dbcon, tablename):
2
dbcur = dbcon.cursor()
3
dbcur.execute("""
4
SELECT COUNT(*)
5
FROM information_schema.tables
6
WHERE table_name = '{0}'
7
""".format(tablename.replace(''', '''')))
8
if dbcur.fetchone()[0] == 1:
9
dbcur.close()
10
return True
11
12
dbcur.close()
13
return False
14