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
MySQLConnection
class. - Creates a
cursor
object. - Executes a SQL query using the
execute()
method of thecursor
object. - Fetches all records from the result set using the
fetchall()
method. - Prints the records.
Helpful links
More of Python Mysql
- How do I access MySQL using Python?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How can I convert a MySQL query to JSON using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I get the number of rows returned when querying a MySQL database with Python?
- How can I use Python MySQL libraries to develop software?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
See more codes...