rank vote url
80 336 196 470 url

如何连接MySQL?

在python程序里如何链接MySQL数据库?


连接MYSQL需要3步

1 安装

你必须先安装MySQL驱动.和PHP不一样,Python只默认安装了SQLite的驱动.最常用的包是MySQLdb但是用easy_install安装很困难.

对于Window用户,你可以获取MySQLdb的exe.

对于Linux,可以下载python-mysqldb(可以用sudo apt-get install python-mysqldb命令直接在命令行下载)

对于Mac用户,可以用Macport下载MySQLdb

2 使用

装完之后重启.这不是强制的,但是这样做可以减少问题.所以请重启.

然后就像用其他包一样:

  1. #!/usr/bin/python
  2. import MySQLdb
  3. db = MySQLdb.connect(host="localhost", # your host, usually localhost
  4. user="john", # your username
  5. passwd="megajonhy", # your password
  6. db="jonhydb") # name of the data base
  7. # you must create a Cursor object. It will let
  8. # you execute all the queries you need
  9. cur = db.cursor()
  10. # Use all the SQL you like
  11. cur.execute("SELECT * FROM YOUR_TABLE_NAME")
  12. # print all the first cell of all the rows
  13. for row in cur.fetchall() :
  14. print row[0]

当然,还有许多用法和选项,我只是举了一个基本的例子.你可以看看文档.A good starting point.

3 高级用法

一旦你知道它是如何工作的,你可能想用ORM来避免手动写入SQL,来把表变成Python对象.Python中最有名的ORM叫做SQLAlchemy

我强烈推荐:你的生活质量肯定能获得提高.

最近在Python里又发现了一个好东西:peewee.它是个非常轻巧的ORM,非常容易安装和使用.我的小项目和独立app都使用它,而那些工具像SQLLAlchemy或者Django用在这里有点小题大做了:

  1. import peewee
  2. from peewee import *
  3. db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy')
  4. class Book(peewee.Model):
  5. author = peewee.CharField()
  6. title = peewee.TextField()
  7. class Meta:
  8. database = db
  9. Book.create_table()
  10. book = Book(author="me", title='Peewee is cool')
  11. book.save()
  12. for book in Book.filter(author="me"):
  13. print book.title
  14. Peewee is cool

这个例子可以运行.除了peewee(pip install peewee)不需要别的的依赖.安装不复杂.它非常cool!