- Machine Learning
- Machine Learning Tutorial
- Getting Started
- Mean Median Mode
- Standard Deviation
- Percentile
- Data Distribution
- Normal Data Distribution
- Scatter Plot
- Linear Regression
- Polynomial Regression
- Multiple Regression
- Scale
- Train-Test
- Decision Tree
- Confusion Matrix
- Hierarchical Clustering
- Logistic Regression
- Grid Search
- Categorical Data
- K-means
- Bootstrap Aggregation
- Cross Validation
- AUC - ROC Curve
- K-nearest neighbors
- Python MySQL
- Python - MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert
- MySQL Select
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Drop Table
- MySQL Update
- MySQL Limit
- MySQL Join
- Python MongoDB
- Python - MongoDB
- MongoDB Get Started
- MongoDB Create DB
- MongoDB Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Drop Collection
- MongoDB Update
- MongoDB Limit
- Selected Reading
- Q&A
Python MySQL Select:
Select From a Table
To select from a table in MySQL, use the "SELECT" statement:
Example
Select all records from the "customers" table, and display the result:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Run example »
Note: We use the fetchall()
method, which fetches all rows from the last executed statement.
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the column name(s):
Example
Select only the name and address columns:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name,
address FROM
customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Run example »
Using the fetchone() Method
If you are only interested in one row, you can use the
fetchone()
method.
The fetchone()
method will return the first row of
the result:
Example
Fetch only one row:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
Run example »