How to run SQL query in MySQL database and prevent SQL injection with Python

2 Answers

0 votes
# c:\Users\user_nm\AppData\Local\Programs\Python\Python35-32\Scripts\pip install mysql-connector
    
import mysql.connector
    
db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database="python_database"
)
   
db_cursor = db.cursor()

sql = "SELECT * FROM workers WHERE first_name = %s"
fn = ("Fox", )

db_cursor.execute(sql, fn)

result = db_cursor.fetchall()
 
for row in result:
    print(row)
 
db.close()

 
'''
run:
  
(1, 'Fox', 'C Programmer')
 
'''

 



answered Dec 1, 2018 by avibootz
edited Dec 1, 2018 by avibootz
0 votes
# c:\Users\user_nm\AppData\Local\Programs\Python\Python35-32\Scripts\pip install mysql-connector
    
import mysql.connector
    
db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database="python_database"
)
   
db_cursor = db.cursor()

fn = "Fox"

db_cursor.execute("SELECT * FROM workers WHERE first_name = '%s';" % fn)

result = db_cursor.fetchall()
 
for row in result:
    print(row)

db.close()
 
 
'''
run:
  
(1, 'Fox', 'C Programmer')
 
'''

 



answered Dec 1, 2018 by avibootz
...