In this Python tutorial, we are going to learn how to insert records to your tables in Microsoft SQL Server.

Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn





Source Code:

import sys
import pypyodbc as odbc

records = [
    ['x', 'Movie', '2020-01-09', 2020], 
    ['y', 'TV Show', None, 2019]
]

DRIVER = 'SQL Server'
SERVER_NAME = 'LAPTOP-JIE'
DATABASE_NAME = 'JJ'

conn_string = f"""
    Driver={{{DRIVER}}};
    Server={SERVER_NAME};
    Database={DATABASE_NAME};
    Trust_Connection=yes;
"""

try:
    conn = odbc.connect(conn_string)
except Exception as e:
    print(e)
    print('task is terminated')
    sys.exit()
else:
    cursor = conn.cursor()


insert_statement = """
    INSERT INTO NetflixMovies
    VALUES (?, ?, ?, ?)
"""

try:
    for record in records:
        print(record)
        cursor.execute(insert_statement, record)        
except Exception as e:
    cursor.rollback()
    print(e.value)
    print('transaction rolled back')
else:
    print('records inserted successfully')
    cursor.commit()
    cursor.close()
finally:
    if conn.connected == 1:
        print('connection closed')
        conn.close()