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 access MySQL using Python?
- How can I connect Python to a MySQL database using an Xserver?
- How can I use Python to retrieve data from MySQL?
- How can I access MySQL using Python?
- How do I install a Python package from PyPI into a MySQL database?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python to interact with a MySQL database using YAML?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How can I connect Python and MySQL?
See more codes...