-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw3school_pythonmysqlwhere.py
More file actions
64 lines (41 loc) · 1.48 KB
/
w3school_pythonmysqlwhere.py
File metadata and controls
64 lines (41 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Python MySQL Where
# Select With a Filter
# When selecting records from a table, you can filter the selection by using the "WHERE" statement:
# Example - Select records where the address is "Park Lane 38": result:
import mysql.connector # import MySQL Connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "mahanta1",
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 Characters
# You can also select the records that starts, includes, or ends with a given letter or phrase.
# Use the % to represent wildcard characters:
# Example - Select records where the address contains the word "way":
"""
sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
"""
# Prevent SQL Injection
# When query values are provided by the user, you should escape the values.
# This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database.
# The mysql.connector module has methods to escape query values:
# Example - Escape query values by using the placholder %s method:
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)