python-mysqlHow can I use Python to load data from MySQL?
To load data from MySQL using Python, you can use the popular MySQL connector library. This library provides an API for connecting to and executing SQL queries on a MySQL database.
To use the library, you first need to install it. You can do this with the following command:
pip install mysql-connector-python
Once the library is installed, you can use the following code to connect to a MySQL database and execute a query:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Execute a query
mycursor.execute("SELECT * FROM customers")
# Fetch the results
myresult = mycursor.fetchall()
# Print the results
print(myresult)
The output of the above code would be a list of tuples, each representing a row in the table:
[(1, 'John', 'Highway 21'),
(2, 'Peter', 'Lowstreet 4'),
(3, 'Amy', 'Apple st 652'),
(4, 'Hannah', 'Mountain 21'),
(5, 'Michael', 'Valley 345')]
The code consists of the following parts:
import mysql.connector
: This imports the MySQL connector library.mydb = mysql.connector.connect()
: This creates a connection to the MySQL database using the provided credentials.mycursor = mydb.cursor()
: This creates a cursor object which can be used to execute queries.mycursor.execute()
: This executes a query on the database.myresult = mycursor.fetchall()
: This fetches the results of the query.print(myresult)
: This prints the results of the query.
For more information on using the MySQL Connector library, please refer to the documentation.
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I connect to MySQL using Python?
- How can I convert data from a MySQL database to XML using Python?
- How can I use Python and MySQL to generate a PDF?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I check the version of MySQL I am using with Python?
- How do I fix a bad MySQL handshake error in Python?
See more codes...