我正在尝试类似的东西:
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")
但是什么也没有发生,有人可以帮助我吗?我正在使用Micrsoft SQL Server Management Studio 2014 Express版本。该代码将在Python中运行。谢谢
使用内置的Cursor.tables方法进行此检查-以下代码示例假定实例化了连接和游标
if cursor.tables(table='TableName', tableType='TABLE').fetchone():
print("exists")
else:
print("doesn't exist")
注意,这与查询INFORMATION_SCHEMA.TABLES在功能上没有什么不同,但是允许代码在不同数据库平台上的可移植性(并且IMO提高了可读性)。
使用SQL Server Native Client 11.0和SQL Server 2014,调用Cursor.tables
仅执行sp_tables系统存储过程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句