小编典典
分三步使用Python 2连接到MYSQL
1-设定
在执行任何操作之前,必须安装MySQL驱动程序。与PHP不同,默认情况下,Python仅安装SQLite驱动程序。最常用的软件包是MySQLdb,但很难使用easy_install进行安装。请注意,MySQLdb仅支持Python 2。
对于Windows用户,你可以获取MySQLdb的exe。
对于Linux,这是一个临时包(python-mysqldb)。(你可以在命令行中使用sudo apt-get install python-mysqldb(对于基于debian的发行版),yum install MySQL-python(对于基于rpm的dnf install python-mysql发行版)或(对于现代的fedora发行版)进行下载。)
对于Mac,你可以使用Macport安装MySQLdb。
2-用法
安装后,重新启动。这不是强制性的,但是如果出现问题,它将阻止我回答本文中的3或4个其他问题。因此,请重新启动。
然后就像使用其他任何软件包一样:
#!/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()
当然,有成千上万种可能性和选择。这是一个非常基本的例子。你将不得不查看文档。一个良好的起点。
3-更高级的用法
一旦知道了它的工作原理,你可能希望使用ORM来避免手动编写SQL并像处理Python对象一样处理表。Python社区中最著名的ORM是SQLAlchemy。
我强烈建议你使用它:你的生活将变得更加轻松。
我最近在Python世界中发现了另一件珠宝:peewee。这是一个非常精简的ORM,设置起来非常简单快捷。对于小型项目或独立应用程序来说,这让我感到欣慰,而在使用SQLAlchemy或Django等大型工具的情况下,这太过残酷了:
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(pip install peewee)外,没有其他要求。
-02-09