Python MySQL Where

时间:2019-09-27
本文章向大家介绍Python MySQL Where,主要包括Python MySQL Where使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

章节


筛选数据

从表中选取记录时,可以使用“WHERE”语句筛选:

示例

选取地址为“Park Lane 38”的记录:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  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)

通配符

WHERE语句中可以使用通配符%。关于SQL中,WHERE子句使用通配符,详情可以参考我们的SQL教程SQL WHERE

示例

选取地址中包含单词“way”的记录:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  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注入,应该转义这些值。

SQL注入是一种常见的web黑客技术,用于破坏或误用数据库。

mysql.connector 模块有方法可以转义查询值:

示例

使用占位符%s方法转义查询值:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  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)

原文地址:https://www.cnblogs.com/jinbuqi/p/11595804.html