1

I want to check whether the table exists or not before inserting the data. This is what i have tried:

def checkTables(tablename):
    stmt = "SHOW TABLES LIKE %s"%tablename          
    cursor.execute(stmt)
    result = cursor.fetchone()          
    return result

But it gives me error saying:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ctg_payload3' at line 1

Abijith Mg
  • 2,647
  • 21
  • 35
tintin
  • 35
  • 2
  • 12
  • Is your syntax right for the parameter? See e.g. http://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python depending on which db you are using, e.g. maybe `cursor.execute("SHOW TABLES LIKE ?", (tablename))` – doctorlove Mar 28 '17 at 11:45

3 Answers3

0

Maybe it is not the best way.

As for my opinion, I will show tables;, then search the result.

And, I you cannot execute show tables like tablename;, no syntax like that.

edit 1

If you must do it in sql, use

 show table status like 'table_name';

' is needed for this sql.

chile
  • 141
  • 1
  • 12
0

Try this query string :SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%' or

this one

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE '%tablename%'

Good luck

kourouma_coder
  • 1,078
  • 2
  • 13
  • 24
0

Try this.

def checkTables(tablename):
    stmt = "SHOW TABLES LIKE '%s' "% ('%'+str(tablename)+'%')
    cursor.execute(stmt)
    result = cursor.fetchone()          
    return result
Abhishake Gupta
  • 2,939
  • 1
  • 25
  • 34