Python Forum

Full Version: New to Python, please help with checking Azure SQL DB for a table
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I've just decided to try and learn Python, I've got very limited experience with programming languages, but have been working with PowerShell for a while so hoping this well help me.

So basically I'm trying to learn Python but developing my own App, I'm trying to get the app to check my Azure SQL DB for a table and if it doesn't exist, create it.

Im trying to use a IF statement to query the DB using the below, Ive excluded the connection details, as i can get the Table created so i know the connction details are good.
sql_check = """
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'employee'"""
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
def check_database_table():
    cursor = cnxn.cursor()
    r = cursor.execute(sql_check)
    print(r)
And then i was going to do something like if r = null then do something, but i do get a value back from r

Hope this makes sense.
you can use 'create table if not exists' it won't destroy current table if already exists.
pyodbc implements python's DB api 2.0, which is documented here, in pep 249. The api says that the return value of cursor.execute() is unspecified. After this statement, you can read the rows of the result by using cursor.fetchone() or cursor.fetchall() for example.
Ok, thanks for the replies. I don't really understand when to use the
cursor.fetchall()
when I try I don't get any output.
After cursor.execute(request) you write rows = cursor.fetchall() for example.