Python MySQL Where
- Previous Page MySQL Select
- Next Page MySQL Order By
استخدام المُرشح لاختيار
يمكنك استخدام جملة "WHERE" لفرز اختيارك عند اختيار السجلات من الجدول:
Example
اختيار السجلات التي تساوي "Park Lane 38"، النتيجة:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address ='Park Lane 38'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)
العلامة المزدوجة
يمكنك أيضًا اختيار السجلات التي تبدأ أو تنتهي بكلمة أو عبارة معينة.
يُرجى استخدام %
يُمثل العلامة المزدوجة
Example
اختيار السجلات التي تحتوي على كلمة "way" في العنوان
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address LIKE '%way%" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)
Prevent SQL Injection
When the user provides query values, you should escape these values.
This is to prevent SQL injection, a common network hacker technique that can damage or abuse your database.
The mysql.connector module has methods to escape query values:
Example
Use the placeholder %s method to escape query values:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address =" %s" adr = ("Yellow Garden 2", ) mycursor.execute(sql, adr) myresult = mycursor.fetchall() for x in myresult: print(x)
- Previous Page MySQL Select
- Next Page MySQL Order By