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 can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to show the MySQL processlist?
- How can I use the MySQL Connector in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python and MySQL to convert fetchall results to a dictionary?
- How do I install a Python package from PyPI into a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
See more codes...