python-mysqlHow can I use Python to make a MySQL request?
You can use Python to make a MySQL request using the MySQL Connector/Python library. The following example code connects to a MySQL database and makes a select query:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
# Create a cursor
my_cursor = mydb.cursor()
# Execute a query
my_cursor.execute("SELECT * FROM customers")
# Fetch all results
result = my_cursor.fetchall()
# Print the results
print(result)
Output example
[(1, 'John', 'Highway 21'), (2, 'Peter', 'Lowstreet 4'), (3, 'Amy', 'Apple st 652'), (4, 'Hannah', 'Mountain 21'), (5, 'Michael', 'Valley 345')]
Code explanation
import mysql.connector
- this imports the MySQL Connector/Python library.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
- this creates a connection to the MySQL database.my_cursor = mydb.cursor()
- this creates a cursor which allows us to execute queries.my_cursor.execute("SELECT * FROM customers")
- this executes a select query to retrieve all records from the customers table.result = my_cursor.fetchall()
- this fetches all the results from the query.print(result)
- this prints the results.
For more information, please refer to the MySQL Connector/Python documentation.
More of Python Mysql
- How do I use Python to query MySQL with multiple conditions?
- How do Python and MySQL compare to MariaDB?
- How do I connect to a MySQL database using Python?
- How can I connect to MySQL using Python?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python to fetch data from a MySQL database?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...