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 do I use Python to query MySQL with multiple conditions?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I connect Python with MySQL using XAMPP?
- How can I use the Python MySQL API to interact with a MySQL database?
- How can I connect Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I check the version of MySQL I'm using with Python?
See more codes...