Skip to content

Instantly share code, notes, and snippets.

@nathairtras
Created May 19, 2019 02:24
Show Gist options
  • Save nathairtras/ffdc94f085d1bd8df09386206889b0d0 to your computer and use it in GitHub Desktop.
Save nathairtras/ffdc94f085d1bd8df09386206889b0d0 to your computer and use it in GitHub Desktop.
Example of using PyTDS with a Table Valued Parameter
import os
import pytds
# Grabbing the user and password from environment variables
# Load these however you would like
server = os.environ["MSSQL_SERVER"]
user = os.environ["MSSQL_USER"]
password = os.environ["MSSQL_PASS"]
# Fake some rows, these could be from CSV
rows = [
["abc"],
["def"],
["ghi"],
]
# Make a connection
with pytds.connect(server=server, user=user, password=password, autocommit=True) as cnx:
# Create a cursor
with cnx.cursor() as cur:
# Create the TVP from the rows
tvp = pytds.TableValuedParam(type_name='dbo.StringList', rows=rows)
# Use the TVP in a query / exec
cur.execute('SELECT * FROM %s', (tvp,))
# Prove we got rows back
print(cur.fetchall())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment