如何在Python中连接MySQL数据库?

1277

我如何使用Python程序连接到MySQL数据库?


50
这里大多数回答都集中在安装MySQLdb库上,我强烈建议选择由MySQL / Oracle提供的MySQL Connector/Python,这将使过程更加简单:https://dev59.com/AnRC5IYBdhLWcg3wOOT1#20959654 - Mr. Napik
10
使用Oracle的Connector/Python存在微妙的错误和其他集成问题。它易于安装,但几乎不可能让它为我尝试过的所有实际用例工作。这就是为什么我总是建议使用MySQLdb的原因。 - Joe C.
8
@Mr.Napik 我使用 pymysql 是因为根据这个比较,它是纯免费的Python。 - Cees Timmerman
我知道高级开发人员看不起w3school的教程,但它们是一个很好的起点。去看看吧! - codingbruh
27个回答

1303

用三个步骤在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)。


47
很高兴你喜欢Peewee!我已经添加了对MySQL的支持,并提供了一些文档,说明如何与之整合。祝你编程愉快! - coleifer
19
请注意,截至本文撰写时,MySQLdb不支持Python 3。Sourceforge页面上显示“即将支持Python 3”,但自2012-10-08以来没有更新。对于Python 3,可以使用PyMySQLoursql - paul

201

这里是一种方法,使用 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()

参考链接


144
如果您不需要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()

15
pip install mysql-connector-python 也可以工作。我没看到哪里写着在 PyPi 上不再支持?如果您的系统没有 gcc/C 编译器,因此无法安装 mysqldb,那么这将非常有用。 - decvalts

130

1
这比使用mysqldb更快吗? - alwbtc
10
是的,没错。而且,我认为它比MySQLdb更方便,API也更好。这应该是答案。 - Anthony
1
使用Python官方的MySQL连接器是节省时间的最佳方式。 - Anas
同意Connector/Python表现良好,比MySQLdb更容易设置,并且有很棒的文档,正如Karthic所提到的。而且它支持Python 3,而MySQLdb目前还不支持。 - twasbrillig
你需要注册这个吗?:/ - J0hnG4lt
3
您可以直接点击登录表单下方的“不,谢谢,直接开始下载”(该按钮似乎是强制性的,但实际上并非如此)。 - ComFreek

126

如果你想避免安装mysql头文件来访问Python中的mysql,请停止使用MySQLDb。

使用 pymysql。它能完成MySQLDb所能做的所有事情,但纯粹使用Python实现,没有任何外部依赖。这使得在各种操作系统上的安装过程始终是一致且容易的。pymysql 可以直接替代 MySQLDb,在我的看法中,没有理由再使用 MySQLDb 了... 永远不用!- 因为在Mac OSX和*Nix系统上安装MySQLDb而导致心理创伤,但这只是我的个人经历。

安装方式

pip install pymysql

就这样...你已经准备好了。

pymysql Github仓库示例用法

import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

另外 - 快速透明地用pymysql替换现有代码中的MySQLdb

如果您有使用MySQLdb的现有代码,可以通过以下简单过程轻松地将其替换为pymysql:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

所有后续对MySQLdb的引用都将通过pymysql透明地使用。


26

尝试使用MySQLdb。MySQLdb仅支持Python 2。

这里有一个如何页面:http://www.kitebird.com/articles/pydbapi.html


来自页面:

# server_version.py - retrieve and display database server version

import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

24
在你的终端中运行以下命令安装MySQL连接器:
pip install mysql-connector-python

在你的 Python 编辑器中运行以下代码以连接到 MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="username",
      passwd="password",
      database="database_name"
)

执行MySQL命令的示例(在您的Python编辑器中):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert, update, delete commands

更多命令请参见:https://www.w3schools.com/python/python_mysql_getstarted.asp


请问您能回答这个问题吗?它只涉及到 mysql-connector。 https://stackoverflow.com/questions/59405740/my-program-is-not-being-able-to-store-values-in-mysql-using-mysql-connector-lib - user11363434
4
有些人已经在那里回答了你的问题。你只是忘记在插入表格值后运行 mydb.commit() - Scott

18

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

使用 mysqlclient 或者 pymysql推荐)。

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

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

请注意,该项目已不再维护,并且不再推送错误修复。


作为数据库驱动程序,还有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上原生运行。

那么如何使用oursql连接mysql?

与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是一个不错的选择,就像其他答案中已经提到的那样。


1
该项目已不再维护;存储库的最后提交日期为2016年。它无法与Python 3.7或更高版本一起使用,因此在任何当前支持的Python版本上都无法使用。 - Martijn Pieters
@MartijnPieters,感谢您提醒我。我已更新答案以反映更为现代化的库。 - bool.dev

15

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()

ORM 方式

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()

14

从Python连接到MySQL的最佳方法是使用MySQL Connector/Python,因为它是与Python一起使用的MySQL的官方Oracle驱动程序,并且适用于Python 3和Python 2。

按照下面提到的步骤连接MySQL:

  1. 使用pip安装连接器

pip install mysql-connector-python

或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序。

  1. 使用mysql connector python的connect()方法连接到MySQL。将必需的参数传递给connect()方法,即主机、用户名、密码和数据库名称。
  2. connect()方法返回的连接对象创建cursor对象以执行SQL查询。
  3. 在工作完成后关闭连接。

例子

import mysql.connector
 from mysql.connector import Error
 try:
     conn = mysql.connector.connect(host='hostname',
                         database='db',
                         user='root',
                         password='passcode')
     if conn.is_connected():
       cursor = conn.cursor()
       cursor.execute("select database();")
       record = cursor.fetchall()
       print ("You're connected to - ", record)
 except Error as e :
    print ("Print your error msg", e)
 finally:
    #closing database connection.
    if(conn.is_connected()):
       cursor.close()
       conn.close()

参考文献 - https://pynative.com/python-mysql-database-connection/

MySQL Connector Python 的重要 API

  • 对于 DML 操作 - 使用 cursor.execute()cursor.executemany() 运行查询语句。之后使用 connection.commit() 将更改持久化到数据库中。

  • 获取数据 - 使用 cursor.execute() 运行查询语句和 cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE) 获取数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接