0

Im trying to pass a string varible to an sql query but I get the following error got tuple instead even though I'm passing a string.

& When I use the following command command = ("INSERT INTO dev.roles (name) VALUES ('student')") it works fine... any feedback is appreciated

import psycopg2
import pandas as pd

con=psycopg2.connect(
    dbname= 'xxxxx', 
    host='xxxxxxxxxxxxxxxxxxxx', 
    port= 'xxxx', 
    user= 'xxxxx', 
    password= 'xxxxxxxxx',
)
cur = con.cursor()

mystr="student"
print("Varible Type: ",type(mystr)) # output: Varible Type:  <class 'str'>
command = ("INSERT INTO dev.roles (name) VALUES (%s)",(mystr)) 
cur.execute(command)
con.commit()

cur.close() 
con.close()

This code outputs the following

Varible Type:  <class 'str'>
Traceback (most recent call last):
  File "myFile.py", line 17, in <module>
    cur.execute(command)
TypeError: argument 1 must be a string or unicode object: got tuple instead
1
  • 1
    command is a tuple, it contains the "INSERT INTO..." string and mystr. Commented May 26, 2020 at 18:28

1 Answer 1

1

Your problem is using the % method of formatting in a way that doesn't abide the syntax.

Keep in mind I don't use pandas so I am providing multiples ways to pass in an argument, although I do use SQLite3.

So, how you want to do it:

command = ("INSERT INTO dev.roles (name) VALUES (%s)" % mystr) 

The .format method:

command = ("INSERT INTO dev.roles (name) VALUES ({})".format(mystr)

Then there is the concatenation method:

command = "INSERT INTO dev.roles (name) VALUES (" + mystr + ")"

Which is harder and adds unnecessary code.

The reason your code doesn't work is because you are setting the value of command to be a two item tuple, this will only ever work if you pass it in directly to the function where this command takes place, for example in SQLite3 there is an execute function, you would pass in a string that executes something.

There is also the first method but as one single string, instead of a tuple of one string:

command = "INSERT INTO dev.roles (name) VALUES (%s)" % mystr
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this helped!

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.