Python MySQL Where
- 上一页 MySQL Select
- 下一页 MySQL Order By
Use a filter to select
When selecting records from a table, you can use the "WHERE" statement to filter the selection:
实例
Select records for "Park Lane 38", results:
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)
Wildcard
You can also choose records that start with, contain, or end with a given letter or phrase.
Please use %
Represents the wildcard:
实例
Select records containing the word "way" in the address:
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)
防止 SQL 注入
当用户提供查询值时,您应该转义这些值。
此举是为了防止 SQL 注入,这是一种常见的网络黑客技术,可以破坏或滥用您的数据库。
mysql.connector 模块拥有转义查询值的方法:
实例
使用占位符 %s 方法来转义查询值:
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)
- 上一页 MySQL Select
- 下一页 MySQL Order By