Home > Back-end >  How do I send a value with SQL commands in python?
How do I send a value with SQL commands in python?

Time:10-13

I use this code:

I want to place the value in the SQL command via the% s operator, but when I reference the change value with% s, the command does not work:

s='amiravira.ir'
q1 = "SELECT DISTINCT name_cat FROM all_user WHERE id='%s' "
mycursor = mydb.cursor()
mycursor.execute( q1 ,s)
myresult = mycursor.fetchall()
myresult

The value can be found only if I write the SQL command line itself. This is exactly the end of my project and it's really weird. I do not know why this happens:

q1 = "SELECT DISTINCT name_cat FROM all_user WHERE id = 'amiravira.ir'"
mycursor = mydb.cursor ()
mycursor.execute (q1, s)
myresult = mycursor.fetchall ()
myresult

I want to know what should I do to send data via SQL statements?

CodePudding user response:

The argument(s) for the execute-call must be passed as an iterable (tuple or list), even if there's only one.

So write instead:

mycursor.execute(q1, (s,))

to pass the argument as an one element tuple.

CodePudding user response:

Eventually my problem was solved like this:

d=("'amiravira.ir'")

q2="SELECT LEFT(name_cat, 15) FROM all_user WHERE {id} ={user}".format(id = "id", user =d )

mycursor.execute(q2)
  • Related