MySQL Where

Python MySQL Where

使用筛选器来选取

从表中选择记录时,可以使用 "WHERE" 语句对选择进行筛选:

实例

选择记录为 "Park Lane 38" 的记录,结果:

import mysql.connectormydb = 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)

运行实例

通配符

您也可以选择以给定字母或短语开头、包含或结束的记录。

请使用 表示通配符:

实例

选择地址中包含单词 "way" 的记录:

import mysql.connectormydb = 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.connectormydb = 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)

运行实例