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

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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

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.