如何在Python中连接MySQL数据库?
我该如何通过一个Python程序连接到MySQL数据库呢?
27 个回答
如果你不需要使用MySQLdb,但愿意接受其他库的话,我非常推荐MySQL提供的MySQL Connector/Python:http://dev.mysql.com/downloads/connector/python/.
这个库只有一个包(大约110k),是纯Python写的,所以不管你用什么系统都可以用,而且安装起来非常简单。你只需要下载,双击,确认一下许可协议,然后就可以开始使用了。完全不需要Xcode、MacPorts、编译或者重启之类的麻烦。
然后你可以这样连接数据库:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""
select 3 from your_table
""")
result = cursor.fetchall()
print result
finally:
cnx.close()
这里有一种方法可以实现这个功能,使用的是 MySQLdb,不过它只支持Python 2版本:
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()
用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
)就可以了。