如何使用python程序连接MySQL数据库?


当前回答

对于较新版本的Python (>=3.6)

使用mysqlclient或pymysql(推荐)。

对于较旧版本的Python (<3.7, 2.4 <= Python <= 2.7)

如果您正在使用较旧版本的Python(不幸的是),那么您也可以尝试-> oursql。

但是请注意,该项目不再维护,错误修复也不会推送。


作为一个db驱动程序,还有oursql。这个链接列出了一些原因,说明了为什么oursql更好:

oursql有真正的参数化,将SQL和数据完全分开发送到MySQL。

Oursql允许文本或二进制数据流进数据库和流出数据库,而不是要求所有内容都缓冲在客户端。 Oursql既可以惰性地插入行,也可以惰性地获取行。 Oursql默认支持unicode。 oursql支持python 2.4到2.7,在2.6+上没有任何弃用警告(见PEP 218),在2.7上也没有完全失败(见PEP 328)。 Oursql在python 3.x上本机运行。

那么如何连接mysql与oursql?

与mysqldb非常相似:

import oursql

db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
    print row[0]

文档中的教程相当不错。

当然,对于ORM来说,SQLAlchemy是一个很好的选择,正如已经在其他答案中提到的那样。

其他回答

SqlAlchemy


SQLAlchemy是Python SQL工具包和对象关系映射器 为应用程序开发人员提供了SQL的全部功能和灵活性。 SQLAlchemy提供了一个完整的著名企业级套件 持久性模式,为高效和高性能而设计 数据库访问,改编成简单的python域语言。

安装

pip install sqlalchemy

原始查询

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

蠕虫方式

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()

用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)即可。

对于python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

我在windows 7上安装了pip,只是 安装cymysql

(你不需要cython) 快速无痛

对于Python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到的结果是:mysqlclient更快。

下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:

select * from FOO;

立即在mysql终端执行: set中有46410行(0.10秒)

pymysql (2 . 4s):

from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_pymysql():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_pymysql()

下面是pymysql的配置文件:

mysqlclient 0.4s)

from profilehooks import profile
import MySQLdb

connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_mysqlclient():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_mysqlclient()

下面是mysqlclient的配置文件:

因此,mysqlclient似乎比pymysql快得多

你可以用这种方式连接你的python代码到mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()