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?
-
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– CS GO2014年11月14日 16:42:11 +00:00Commented 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\$xDaevax– xDaevax2014年11月14日 17:12:14 +00:00Commented Nov 14, 2014 at 17:12
-
\$\begingroup\$ @xDaevax Input will come from the user through subscriber form \$\endgroup\$CS GO– CS GO2014年11月14日 17:15:25 +00:00Commented Nov 14, 2014 at 17:15
2 Answers 2
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.
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.
Explore related questions
See similar questions with these tags.