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?

\$\endgroup\$
  • 1
    \$\begingroup\$ @200_success this is the real code i am using for subscribers list. i have changed some of the database info \$\endgroup\$ – CS GO Nov 14 '14 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\$ – xDaevax Nov 14 '14 at 17:12
  • \$\begingroup\$ @xDaevax Input will come from the user through subscriber form \$\endgroup\$ – CS GO Nov 14 '14 at 17:15
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.

\$\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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.