python - Pyodbc- If table exist then don't create in SSMS -
i trying like:
import pyodbc cnxn = pyodbc.connect(driver ='{sql server}' ,server ='host-mobl\instance',database ='dbname', trusted_connection = 'yes' ) cursor = cnxn.cursor() cursor.execute("""select * information_schema.tables table_name = n'tablename'""") def checktableexists(cnxn, tablename): cursor = cnxn.cursor() cursor.execute(""" select count(*) information_schema.tables 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 nothing happen, can me on this? using micrsoft sql server management studio 2014 express version. code run in python. thank
use built-in cursor.tables method check - following code sample assumes connection , cursor instantiated
if cursor.tables(table='tablename', tabletype='table').fetchone(): print("exists") else: print("doesn't exist")
note isn't functionally different querying information_schema.tables, allows code portability different database platforms (and imo improves readability).
using sql server native client 11.0 , sql server 2014, calling cursor.tables
executes sp_tables system stored procedure.
Comments
Post a Comment