0

In order to parse the values of variables a and b in the field username and password respectively of table admin_details I tried this method the pseudo code is something like below:

...
...
a=4
b=8
....
....
cur.execute("INSERT INTO admin_details(username, password)  VALUES('%s','%s'), %(a,b)")
....

I get the value inserted in the table as
username: 4
password:8

But in order to insert the characters like**
a=' john'
b='snow'
in the admin_details field. I tried using tuples as below

a='john'
b='snow'
tup=['a','b']

and to insert this tuple's value a and b in the table i tried all the possible ways but still I am not able to store the variables in the table.

cur.execute("INSERT INTO admin_details(username, password)  VALUES('%s','%s'), % ['a','b']")

But I get this

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTO INTO admin_details(username) VALUES('%s'), %('entry1.get()')' at line 1")
sigdelsanjog
  • 528
  • 1
  • 11
  • 30

2 Answers2

2

Do not attempt to use string formatting for constructing SQL queries. Pass query parameters in the second argument to execute() - this way you'll protect yourself against sql injection problems:

a = 'john'
b = 'snow'
cur.execute("INSERT INTO admin_details(username, password) VALUES(%s, %s)", (a, b))

Note that in this case you also don't need quotes around the placeholders in the query.

See also:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

I think use this way to insert mysql data should be better:

insert_sql = 'INSERT INTO admin_details(username, password)  VALUES("{0}","{1}")'.format(*tup)
cur.execute(insert_sql)
conn.commit()
lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30