Using an application written in Python, how can I connect to a MySQL Database?
original question:
- How do I connect to a MySQL Database in Python? formulated by Marc Lincoln
Using an application written in Python, how can I connect to a MySQL Database?
original question:
Connecting to MySQL using Python in 3 steps
Configuration :
You must install the driver for MySQL before doing anything. Unlike PHP, only the driver for SQLite is installed by default in Python. The most used package to do this is MySQLdb but it is a bit difficult to install using
easy_install
.For Windows users, you can download a MySQLdb exe .
For Linux, it is a casual package (
python-mysqldb
). You can use on the command linesudo apt-get install python-mysqldb
for Debian based distributions oryum install mysql-python
for RPM based distributions.For MAC, you can install MySQLdb using Macport .
Use:
After installation, reboot the system. This is not required, but it will prevent you from answering another 3 or 4 questions if something goes wrong. So please restart.
Then it's just like using any other package:
Of course there are thousands of possibilities and options; this is a pretty basic example. You'll have to read the documentation. A good starting point .
More advanced usage:
Once you know how it works, you can use an ORM to avoid writing SQL statements manually and manipulating tables as if they were Python objects. The most famous ORM in the Python community is SQLAlchemy .
I really recommend you to use it - your life will be much easier.
I recently discovered another gem in the Python world: peewee . It is a fairly light ORM, really simple and fast to configure and use. It helped me a lot in small projects or stand alone applications, where the use of big tools like SQLAlchemy and Django can be excessive:
This example works as a usability example. Nothing more than having installed
peewee
(pip install peewee
:-)) is required. No complicated settings. It's excellent.original answer:
If you are using a current version of Python, the alternative is to use mysqlclient which is a fork of MySQLdb1 and supports Python 2.7 and >3.3.
Facility:
From the command line:
Examples:
Another more pythonic way to make the connection is through the with statement , which is responsible for ensuring that the connection is correctly released:
Links: