Python MySQL Select From
To select data from mysql table, you must have some basic knowledge of SQL SELECT command.
The SELECT
command is used to select data from Mysql tables.
The following syntax is used to select data with limited columns from a table :
SELECT column_name(s) FROM table_name
You can select ALL columns from the table with the *
character:
SELECT * FROM table_name
You can use more options with SELECT
statement to filter data using WHERE
clause, getting ascending or descending ordered result using ORDER BY
keyword, limiting
the query result using LIMIT
clause and more.
Select From a Table - fetchall() and fetchone() methods
We will take a sample table called "books" and it contains three columns ("id", "name", and "price") and three records.
ID | Name | Price |
---|---|---|
14 | Python Networking | 160.00 |
15 | Web Programming | 70.00 |
16 | The Web with Python | 120.00 |
The fetchall()
method is used to return query results and each record as a python tuple.
Example :- Select all books from "books" table :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM books")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(15, 'Web Programming', 70.0)
(16, 'The Web with Python', 120.0)
Note : We utilise a function fetchall()
, which retrieves all rows from the last statement executed.
Selecting Columns
Use the "SELECT" statement followed by the Column name(s) to select just some of the columns in a table :
Example :- Select only columns of id and price :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT id, price FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(15, 70.0)
(16, 120.0)
Using the fetchone() Method
You can use fetchone()
method if you are only interested in one row.
The first row of result is returned with fetchone()
method :
Example :- Fetch only one row from the query results
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM books")
myresult = mycursor.fetchone()
print(myresult)
Output :-
Python MySQL Where
To filter records, the WHERE
clause with SELECT
command is utilized.
The WHERE
keyword only allows records that meet a specific requirement to be extracted.
The following statement is used to filter data from a table is :
SELECT column_name(s) FROM table_name WHERE column_name operator value
Related Links
Select With a Filter
You can filter the selection with the "WHERE" statement when you choose the record from a table :
Example :- Filter books by id = 15 and Filter books by price > 100 :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
# Filter books by id = 15
mycursor.execute("SELECT * FROM books WHERE id = 15")
myresult = mycursor.fetchall()
print("Filter books by id = 15\n")
for x in myresult:
print(x)
# Filter books by price > 100
mycursor.execute("SELECT * FROM books WHERE price > 100")
myresult2 = mycursor.fetchall()
print("\nFilter books by price > 100\n")
for x in myresult2:
print(x)
Output :-
(15, 'Web Programming', 70.0)
Filter books by price > 100
(14, 'Python Networking', 160.0)
(16, 'The Web with Python', 120.0)
Wildcard Characters
The records that start, include or end with a certain letter or phrase can also be selected.
Use the %
to represent the characters of the wildcards :
Example :- Select records where the word "web" is found in the name column :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM books WHERE name Like '%web%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(16, 'The Web with Python', 120.0)
Prevent SQL Injection
If the user provides query values, the values should be escape.
This prevents SQL injections, a frequent approach for web hacking, to remove or misuse your database.
Methods to avoid query values in the mysql.connector module :
Example :- Escape query values utilising the %
technique of placholder :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
qry = "SELECT * FROM books WHERE name Like %s and price > %s"
val = ("%python%", 150)
mycursor.execute(qry, val)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
Python MySQL Order By
To arrange the result in ascending or descending order, use the ORDER BY declaration.
By default, the term ORDER BY orders the result up. Use the DESC
keyword to sort the output in decreasing order.
Related Links
Sort the Result
The following syntax is used to sort a query result :
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Example :- Display results in ascending order based on price column :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM books ORDER BY price"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(16, 'The Web with Python', 120.0)
(14, 'Python Networking', 160.0)
ORDER BY DESC
To sort the result in a descending order, use the DESC
keyword.
Example :- Numerically sort the result reverse by id column :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY id DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(15, 'Web Programming', 70.0)
(14, 'Python Networking', 160.0)
Python MySQL Limit
The LIMIT
clause in MySQL is used to limit how many records are returned from query results.
LIMIT Data highly useful on big tables to easily implement pagination results with SQL. A huge quantity of data can have an effect on performance.
Suppose we would like to pick from the "books" table all records from 1 - 20 (included)." The SQL query looks like that :
$sql = "SELECT * FROM books LIMIT 20";
Limit the Result
Using the statement "LIMIT", you can reduce the number of records you return from the query :
Example :- In the table "books" choose the first 2 records :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM books LIMIT 2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
(15, 'Web Programming', 70.0)
Start From Another Position
You can use the "OFFSET" keyword if you wish to return 5 files beginning with the third record :
Example :- Return 1 record from start position 2 :
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :-
Python MySQL Join Two or More Tables
It is possible to work with multiple tables in python with mysql.
You can use JOIN statements to merge rows from two or more tables based on a related column.