Search code examples
pythonsqlpymssql

Insert record and map strings to fields?


Im brand new to python and SQL, but enjoying the learning curve.

I am making use of pymssql and have what I imagine will be a fairly basic issue.

Within a function, I need to INSERT one record in a table, and pass into the INSERT statement some variables I calculated earlier.

Currently my code looks like this:

var 1 = "Hello"
var 2 = "Bye"
var 3 = "12/12/12
cursor.execute("INSERT INTO table (field1, field2, field3) VALUES(%s, %s, %s)", var1, var2, var3)

This returns an error:

execute() takes at most 2 positional arguments (4 given)

What am I doing wrong, and bearing in mind I am learning, what would be a more elegant way of doing this?


Solution

  • You are passing in each argument separately to execute(), where it only takes two.

    cursor.execute("INSERT INTO table (field1, field2, field3) VALUES(%s, %s, %s)",
                   (var1, var2, var3))
    

    Now, you are passing it two arguments. The first is a string, and the second is a tuple of your variables (notice the extra ()).