Pyodbc- 如果 table 存在则不要在 SSMS 中创建

Pyodbc- If table exist then don't create in SSMS

我正在尝试类似的东西:

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 中的 运行。 谢谢

这是一个简单的例子:

import pyodbc

conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=yourserver.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_password;TDS_Version=7.2;')
cursor = conn.cursor()

cursor.execute("""
    IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'your_table_name')
    BEGIN
        SELECT 'Your table exists.' AS result
    END
""")

rows = cursor.fetchall()
for row in rows:
    print(row.result)

为我打印 "Table Exists"。您应该可以根据自己的需要对其进行修改。

使用内置 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系统存储过程。