1

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

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot! This is what I was looking for.
I have one variable like Companyname and want to insert in each row. how can I pass one variable name in above ? ... values (?, ?, ?, ?, ?,'Google'). it is working, but I want the company name as a variable to pass into SQL.I do not want to insert company name in each Tuple.
"I do not want to insert company name in each Tuple" -- Why not? It's easy: tmpData=[tup+(Companyname,) for tup in tmpData]
Thanks. I want to insert some 5+ other variables like ( Dept, Auth, Class etc). so this might be cumbersome?? I can add this 5 times. Please suggest.
I don't see what's cumbersome about tmpData=[tup+(Companyname, Dept, Auth, Class, Foo, Bar) for tup in tmpData]. Just make sure you have the same number of ? in sql as the number of items in your tuples.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.