Reputation: 203
I have created the Tuple as below. I want to insert the follwoing into the SQL database (using import pyodbc).
tmpData=[('PRP', 'PRP-000005', 'In Progress', 'UYR', 'uYT'), ('PRP', 'PRP-000006', 'In Progress', 'UYR', 'uYT'), ('PRP', 'PRP-000007', 'In Progress', 'UYR', None), ('PRP', 'PRP-000008', 'In Progress', 'UYR', 'TCP'), ('PRP', 'PRP-000009', 'In Progress', 'UYR', 'OTH'), ('PRP', 'PRP-000010', 'In Progress', 'UYR', None),]
conn = pyodbc.connect('Driver={SQL Server};'
'Server=Python;'
'Database=Test;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql = "insert into [TBListformstables] values???????
cursor.execute(sql)
I am facing a problem in writing this to SQL. What would come at values so that Tuple can be passed
Upvotes: 1
Views: 3219
Reputation: 943
You can create a JSON object from your list and pass it to the insert query. Check below:
sql = insert into table values(json.dumps(tmpData))
Upvotes: 1
Reputation:
See executemany
Executes the same SQL statement for each set of parameters, returning None. The single params parameter must be a sequence of sequences, or a generator of sequences.
params = [ ('A', 1), ('B', 2) ]
cursor.executemany("insert into t(name, id) values (?, ?)", params)
So in your example, something like
sql = "insert into [TBListformstables] values (?, ?, ?, ?, ?)"
cursor.executemany(sql, tmpData)
Upvotes: 1