Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying something like:

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")

But there is nothing happen, can anyone help me on this? I am using Micrsoft SQL Server Management Studio 2014 Express version. The code will be run in Python. Thank you

like image 498
Dsw Wds Avatar asked Apr 19 '16 02:04

Dsw Wds


2 Answers

Use the built-in Cursor.tables method for this check - following code sample assumes connection and cursor are instantiated

if cursor.tables(table='TableName', tableType='TABLE').fetchone():
    print("exists")
else:
    print("doesn't exist")

Note this isn't functionally different from querying INFORMATION_SCHEMA.TABLES, but allows code portability with different database platforms (and IMO improves readability).

Using SQL Server Native Client 11.0 and SQL Server 2014, calling Cursor.tables just executes the sp_tables system stored procedure.

like image 136
Bryan Avatar answered Oct 10 '22 13:10

Bryan


Here's a simple example:

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)

That prints "Table Exists" for me. You should be able to modify it to your needs.

like image 4
FlipperPA Avatar answered Oct 10 '22 12:10

FlipperPA