python-mysqlHow can I use a Python MySQL cursor to access data from a database?
The cursor object in Python is used to interact with databases. It allows you to execute SQL queries, fetch data from the result sets, call procedures, and more. To use a Python MySQL cursor to access data from a database, you need to first create a connection to the database. This can be done using the connect() method of the MySQLConnection class.
Example code
from mysql.connector import MySQLConnection, Error
# Connect to the database
db_connection = MySQLConnection(user='root', password='password',
host='localhost', database='test')
# Create a cursor object
cursor = db_connection.cursor()
Once the connection is established, you can use the execute() method of the cursor object to execute any SQL query. For example, to select all records from a table named users, the following code can be used:
# Execute query
cursor.execute("SELECT * FROM users")
# Fetch all records
records = cursor.fetchall()
# Print records
print(records)
Output example
[(1, 'John', 'Smith'), (2, 'Jane', 'Doe'), (3, 'Bob', 'Jones')]
The code above:
- Establishes a connection to the database using the
MySQLConnectionclass. - Creates a
cursorobject. - Executes a SQL query using the
execute()method of thecursorobject. - Fetches all records from the result set using the
fetchall()method. - Prints the records.
Helpful links
More of Python Mysql
- How can I create a web application using Python and MySQL?
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How do I connect Python with MySQL using XAMPP?
- How do I insert JSON data into a MySQL database using Python?
- How can I connect Python and MySQL?
- How do I connect to XAMPP MySQL using Python?
- How can I use Yum to install the MySQLdb Python module?
See more codes...