2
\$\begingroup\$

I'm new to Python and I am learning database connections from here.

This is the code I am using to insert e-mail subscribers into a table:

conn = mysql.connector.connect(user="user", password="password", host="127.0.0.1", database="db")
cursor = conn.cursor()
query = ("INSERT INTO test(name,email) VALUES(%s,%s)")
data = ("cool", "cool")
cursor.execute(query, data)
conn.commit()
cursor.close()
conn.close()

Is this type of data insertion safe and can stop SQL injections?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 14, 2014 at 16:20
\$\endgroup\$
3
  • 1
    \$\begingroup\$ @200_success this is the real code i am using for subscribers list. i have changed some of the database info \$\endgroup\$ Commented Nov 14, 2014 at 16:42
  • \$\begingroup\$ In order to inject SQL, there needs to be user input going into the query, where will your user input come from? Your code does not make this clear, other than the hard-coded "cool" values. \$\endgroup\$ Commented Nov 14, 2014 at 17:12
  • \$\begingroup\$ @xDaevax Input will come from the user through subscriber form \$\endgroup\$ Commented Nov 14, 2014 at 17:15

2 Answers 2

3
\$\begingroup\$

You've got the right idea! By passing the values in along with the query you're doing what other languages call a "prepare" on the final query to make sure that the values being passed are quoted/escaped properly to avoid issues with injection.

answered Nov 14, 2014 at 18:24
\$\endgroup\$
2
\$\begingroup\$
query = ("INSERT INTO test(name,email) VALUES(%s,%s)")

You've constructed a string describing a SQL query with parameters.

data = ("cool", "cool")

You've created a tuple of parameter values equal in length to the number of parameters specified in your query.

cursor.execute(query, data)

You've called the parameterized query method of the cursor object with your parameterized query string and your tuple of parameters.

I'm not a seasoned pythoner, but looking at the documentation, it appears that you have properly parameterized your query. I would give you a sign off on this code.

answered Nov 14, 2014 at 18:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.