Python MySQL Where


chapter


Screening data

When selecting records from a table, you can use the "WHERE" statements Filter:

Examples

Select record address "Park Lane 38" in:

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)

Tsuhaifu

WHEREStatement can use wildcards %. About the SQL, WHERE clause uses a wildcard, the details can refer to our SQL Tutorial SQL WHERE

Examples

Select an address record contains the word "way" of:

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)

Prevent SQL injection

When users query a value, in order to prevent SQL injection , these values should be escaped.

SQL injection is a common web hacking techniques used to destroy or misuse database.

mysql.connector module there are ways to escape query value:

Examples

Placeholder %smethod escape query value:

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)

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11595804.html