How to connect MySQL databases in Python

Asked 2 years ago, Updated 2 years ago, 33 views

Please tell me how to access the MySQL database using the Python program.

mysql python

2022-09-22 13:12

1 Answers

1 - Settings

First, you must install the MySQL driver. Unlike PHP, Python has only SQLite drivers installed by default. The most commonly used package is MySQLdb, which is difficult to install even with easy_install.

For Windows users, you can download the exe file from MySQLdb.

For Linux, python-mysqldb is provided as a package. You can get the command by entering sudo apt-get install python-mysqldb for the Debian family, yum install mysql-python for the rpm family, and dnf install python-modes for the modern fedora.

Finally, the Mac can be installed using the Mac port.

2 - How to Use

After installation, restart the computer first. Although it is not an essential part, we recommend that you restart because there are occasional problems that may arise if you do not restart.

Then, you can just use it as below like other packages :

Of course, this is just the most basic example, and there are various possibilities and settings. Please refer to this document.

3 - Deepened Use

Once you've learned how to work, you'll want to use ORM to prevent manual writing of SQL and to use tables as if they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

If you want to work more comfortably, I strongly recommend using it.

Personally, I recently learned about a library called peewee, which is a light ORM that is very easy and fast to install. SQLAlchemy or Django can be very useful when creating small projects or independent forms of apps that seem a little too much.

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

Peewee is cool

The example above is an example that is available. There is nothing else to do except install peeewee (pip install peeewee).


2022-09-22 13:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.