where 条件语句
如果我们要读取指定条件的数据,可以使用 where 语句:
demo_mysql_test.py
读取 name 字段为 RUNOOB 的记录:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()sql = "SELECT * FROM sites WHERE name ='RUNOOB'"mycursor.execute(sql)myresult = mycursor.fetchall()forxinmyresult: print(x)
执行代码,输出结果为:
(1,'RUNOOB','https://www.runoob.com')
也可以使用通配符 %:
demo_mysql_test.py
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()sql = "SELECT * FROM sites WHERE url LIKE '%oo%'"mycursor.execute(sql)myresult = mycursor.fetchall()forxinmyresult: print(x)
执行代码,输出结果为:
(1,'RUNOOB','https://www.runoob.com')
(2,'Google','https://www.google.com')
为了防止数据库查询发生 SQL 注入的攻击,我们可以使用 %s 占位符来转义查询的条件:
demo_mysql_test.py
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()sql = "SELECT * FROM sites WHERE name = %s"na = ("RUNOOB", )mycursor.execute(sql, na)myresult = mycursor.fetchall()forxinmyresult: print(x)