To connect to a MySQL database using Python, you'll need to install the MySQL connector. While Python includes the SQLite driver by default, MySQL requires an additional package. The recommended connector, MySQLdb, provides a straightforward installation process.
For Windows users, an executable (.exe) for MySQLdb is available. Linux users can retrieve the package using their package manager (e.g., apt-get, yum, or dnf). Mac users can utilize Macport for MySQLdb installation.
Once the connector is installed, you're ready to connect to the database. Utilize the MySQLdb.connect() function, providing the necessary credentials: hostname (often "localhost"), username, password, and database name.
Here's an example:
import MySQLdb db = MySQLdb.connect(host="localhost", user="john", passwd="mypassword", db="mydatabase")
This establishes a connection to the "mydatabase" database using the specified credentials.
With a connection established, create a Cursor object to execute queries. This object enables database interactions, including data retrieval and manipulation.
For instance, to retrieve all rows from a table named "customers," execute the following:
cur = db.cursor() cur.execute("SELECT * FROM customers")
The results can then be iterated over using the fetchall() method.
for row in cur.fetchall(): # Iterate over each row's data
For more complex scenarios, consider using an Object-Relational Mapping (ORM) tool such as SQLAlchemy or peewee. These ORM frameworks abstract away the need for manual SQL coding, providing an object-oriented approach to database interaction.
Here's a quick example using peewee to create a model and manipulate data:
from peewee import * db = MySQLDatabase('mydb', user='john', passwd='mypassword') class Person(Model): name = CharField() age = IntegerField() class Meta: database = db person = Person(name="John Doe", age=30) person.save()
This creates a "Person" model, adds a record to the database, and retrieves the information using an object-oriented interface.
The above is the detailed content of How Can I Establish a MySQL Database Connection in Python?. For more information, please follow other related articles on the PHP Chinese website!