How do I connect to a MySQL Database in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

How do I connect to a MySQL database using a python program?

Answers


Connecting to MYSQL with Python in 3 steps

  1 - Setting   

http://pypi.python.org/pypi/MySQL-python/ http://pypi.python.org/pypi/MySQL-python/

http://sourceforge.net/project/showfiles.php?group_id=22307 http://sourceforge.net/project/showfiles.php?group_id=22307

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476 http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476

  2 - Usage   

After installing, reboot. This is not mandatory, but will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using another package :

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

http://www.mikusa.com/python-mysql-docs/ http://www.mikusa.com/python-mysql-docs/

  3 - More advanced usage   

http://www.sqlalchemy.org/ http://www.sqlalchemy.org/

I strongly advise you to use it: your life is going to be much easier.

http://peewee.readthedocs.org/en/latest/index.html http://peewee.readthedocs.org/en/latest/index.html

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

This example works out of the box. Nothing other than having peewee (pip install peewee :-)) is required. No complicated setup. It s really cool.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils