ChatGPT解决这个技术问题 Extra ChatGPT

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

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

这里的大多数答案都集中在安装 MySQLdb 库上,我真的建议选择 MySQL/Oracle 提供的 MySQL Connector/Python,这使得过程更加简单:stackoverflow.com/questions/372885/…
使用 Oracle 的连接器/Python 的问题在于它存在细微的错误和其他集成问题。它易于安装,但几乎不可能适用于我尝试过的所有实际用例。因此我总是推荐 MySQLdb。
@Mr.Napik 我使用 pymysql 因为它是根据 this comparison 的纯免费 Python。

2
22 revs, 19 users 70%

三步使用 Python 2 连接到 MYSQL

1 - 设置

在执行任何操作之前,您必须安装 MySQL 驱动程序。与 PHP 不同,Python 默认只安装 SQLite 驱动程序。最常用的软件包是 MySQLdb,但很难使用 easy_install 安装它。请注意 MySQLdb 仅支持 Python 2。

对于 Windows 用户,您可以获得 exe of MySQLdb

对于 Linux,这是一个临时包(python-mysqldb)。 (您可以在命令行中使用 sudo apt-get install python-mysqldb(对于基于 debian 的发行版)、yum install MySQL-python(对于基于 rpm)或 dnf install python-mysql(对于现代 fedora 发行版)进行下载。)

对于 Mac,您可以install MySQLdb using Macport

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

当然,有上千种可能性和选择;这是一个非常基本的例子。您将不得不查看文档。 A good starting point

- 更高级的用法

一旦您知道它的工作原理,您可能希望使用 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) 外,没有其他要求。


很高兴你喜欢小便!!我添加了对 MySQL 的支持以及一些与它集成的documentation。快乐黑客!
请注意,在撰写本文时,MySQLdb 不支持 Python 3。sourceforge 页面显示“即将推出 Python 3 支持”,但自 2012-10-08 以来一直没有更新。对于 Python 3,有 PyMySQLoursql
F
Flimm

这是使用仅支持 Python 2 的 MySQLdb 的一种方法:

#!/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()

Reference here


E
Eric Leschinski

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

pip install mysql-connector-python 也可以。我没有看到它说 PyPi 不再支持?如果您无法访问系统上的 gcc/C 编译器,因此无法安装 mysqldb,那就太好了。
A
Alon Barad

Oracle (MySQL) 现在支持纯 Python 连接器。这意味着无需安装二进制文件:它只是一个 Python 库。它被称为“连接器/Python”。

http://dev.mysql.com/downloads/connector/python/

安装后可以看到一些使用示例here


这比使用 mysqldb 快吗?
是的。此外,它比 MySQLdb 更容易,而且我认为 API 更好。这应该是答案。
使用python的官方mysql连接器是赢得时间的最佳方式
同意 Connector/Python 运行良好,比 MySQLdb 更容易设置,并且有很好的文档,正如上面提到的 Karthic。它支持 Python 3,而 MySQLdb 还没有。
@J0hnG4lt 您只需单击登录表单下方的“不,谢谢,开始我的下载”(这实际上似乎是强制性的,但不是)。
P
Phillip

如果您想避免安装 mysql 标头只是为了从 python 访问 mysql,请停止使用 MySQLDb。

使用 pymysql。它完成了 MySQLDb 所做的所有事情,但它纯粹是在 Python 中实现的,NO External Dependencies。这使得所有操作系统上的安装过程一致且容易。 pymysql 是 MySQLDb 的替代品,恕我直言,没有理由将 MySQLDb 用于任何事情......永远! - PTSD from installing MySQLDb on Mac OSX and *Nix systems,但那只是我。

安装

pip install pymysql

就是这样......你准备好玩了。

来自 pymysql Github repo 的示例用法

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

ALSO - 快速透明地替换现有代码中的 MySQLdb

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

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

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


F
Flimm

尝试使用 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 ()

S
Scott

在终端中运行此命令以安装 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 相关。 stackoverflow.com/questions/59405740/…
有些人已经在那里回答了你的问题。您只是在将值插入表后忘记运行 mydb.commit()
b
bool.dev

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

使用 mysqlclientpymysql推荐)。

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

如果您正在使用旧版本的 Python(很遗憾),那么您也可以尝试一下 -> oursql

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

作为 db 驱动程序,还有 oursql。该链接上列出的一些原因说明了为什么我们的sql更好:

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]

tutorial in the documentation 相当不错。

当然对于 ORM SQLAlchemy 是一个不错的选择,正如其他答案中已经提到的那样。


该项目不再被维护;对存储库的最后一次提交是在 2016 年。它不适用于 Python 3.7 或更高版本,因此不再可用于任何当前支持的 Python 版本。
@MartijnPieters 感谢您让我注意到这一点。我已经更新了答案以反映更多最新的库。
A
Anand Tripathi

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

V
Vishal Hule

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

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

使用 pip pip install mysql-connector-python 安装连接器

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

使用 mysql 连接器 python 的 connect() 方法连接到 MySQL。将所需的参数传递给 connect() 方法。即主机、用户名、密码和数据库名称。从 connect() 方法返回的连接对象创建游标对象以执行 SQL 查询。工作完成后关闭连接。

例子:

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 连接器 Python 的重要 API

对于 DML 操作 - 使用 cursor.execute() 和 cursor.executemany() 运行查询。并在此之后使用 connection.commit() 将您的更改持久化到 DB

获取数据 - 使用 cursor.execute() 运行查询并使用 cursor.fetchall()、cursor.fetchone()、cursor.fetchmany(SIZE) 来获取数据


M
Mahdi

尽管有上述所有答案,但如果您不想预先连接到特定数据库,例如,如果您仍想创建数据库 (!),您可以使用 connection.select_db(database),如下所示。

import pymysql.cursors
connection = pymysql.connect(host='localhost',
                         user='mahdi',
                         password='mahdi',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()

T
Tanner Clark

尽管你们中的一些人可能会将其标记为重复并且对我复制别人的答案感到不安,但我真的很想强调 Napik 先生的回应的一个方面。因为我错过了这个,我造成了全国性的网站停机(9分钟)。如果只有某人共享此信息,我本可以阻止它!

这是他的代码:

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

这里重要的是 Try 和 finally 子句。这允许始终关闭与代码的游标/sqlstatement 部分中发生的情况的连接。大量活动连接会导致 DBLoadNoCPU 达到峰值,并可能导致数据库服务器崩溃。

我希望这个警告有助于拯救服务器并最终拯救工作! :D


m
muhuk

MySQLdb 是直接的方式。您可以通过连接执行 SQL 查询。时期。

我的首选方式(也是 pythonic)是使用强大的 SQLAlchemy 代替。这是一个 query related 教程,这是一个关于 SQLALchemy 的 ORM capabilities 的教程。


链接已失效,您可以查看并使用正确的链接进行更新吗?
抱歉,截至 2020 年 6 月,您的最后两个链接仍然无效。
k
kai

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

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

原始 sql:select * from FOO;

立即在 mysql 终端中执行:46410 rows in set (0.10 sec)

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

https://i.stack.imgur.com/73xiO.png

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

https://i.stack.imgur.com/Ozf0B.png

所以,似乎 mysqlclient 比 pymysql 快得多


H
Hafiz Muhammad Shafiq

只是对上述答案的修改。只需运行此命令即可为 python 安装 mysql

sudo yum install MySQL-python
sudo apt-get install MySQL-python

记住!它区分大小写。


我通过 yum install 安装了 MySQL-python。安装已完成,但我无法导入 MySQLdb 模块。它说没有这样的模块。知道为什么会这样吗?
当您说“高于答案”时,尚不清楚您指的是哪个答案。请使您的答案本身完整。如果您想参考其他答案,请链接到具体答案。
U
Umer

mysqlclient 是最好的,因为其他人只提供对特定版本的 python 的支持

 pip install mysqlclient

示例代码

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

https://github.com/PyMySQL/mysqlclient-python


+1 为 python 3 提出最快的解决方案。但是,mysql.connector_mysql 都给出了导入错误(尽管第二个选项应该根据文档工作)。 import MySQLdb 有效,然后 MySQLdb.connect...
m
michip96

另请查看 Storm。它是一个简单的 SQL 映射工具,可让您轻松编辑和创建 SQL 条目,而无需编写查询。

这是一个简单的例子:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

查找和对象使用:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

用主键查找:

print store.get(User, 1).name #Mark

有关详细信息,请参阅 tutorial


A
Aditya

这是 Mysql 数据库连接

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST']) 
def index():
    if request.method == "POST":
        details = request.form
        cur = mysql.connection.cursor()
        cur.execute ("_Your query_")
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

H
Haider Ali

您可以通过这种方式将您的 python 代码连接到 mysql。

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

cursor = db.cursor()

M
Milovan Tomašević

PyMySQL 0.10.1 - 发布:2020 年 9 月 10 日,也支持 python3。

python3 -m pip install PyMySQL

简单代码:

import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')

# Create a Cursor object
cur = conn.cursor()

# Execute the query
cur.execute("SELECT * FROM fax.student")

# Read and print records
for row in cur.fetchall():
    print(row)

输出:

(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')

太棒了! :)
C
Code GUI

获取库的第一步:打开终端并执行 pip install mysql-python-connector。安装后进行第二步。

导入库的第二步:打开您的 python 文件并编写以下代码:import mysql.connector

第三步连接服务器:编写如下代码:

conn = mysql.connector.connect(host=你的主机名,比如 localhost 或 127.0.0.1,username=你的用户名,比如 root,password = 你的密码)

第三步 制作游标:制作游标让我们很容易运行查询。要使光标使用以下代码:cursor = conn.cursor()

执行查询:要执行查询,您可以执行以下操作:cursor.execute(query)

如果查询更改了表中的任何内容,您需要在执行查询后添加以下代码:conn.commit()

从查询中获取值:如果您想从查询中获取值,您可以执行以下操作:cursor.excecute('SELECT * FROM table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)

fetchall() 方法返回一个包含许多元组的列表,这些元组逐行包含您请求的值。

关闭连接:要关闭连接,您应该使用以下代码:conn.close()

处理异常:要处理异常,您可以使用以下方法:try: #Logic pass except mysql.connector.errors.Error: #Logic pass 要使用数据库:例如,您是一个帐户创建系统,您将数据存储在名为 blabla 的数据库中,您只需添加一个数据库参数到 connect() 方法,比如

mysql.connector.connect(database = 数据库名称)

不要删除主机、用户名、密码等其他信息。


L
Lazik

对于python 3.3

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

我在我的 Windows 7 上安装了 pip,只需 pip install cymysql

(你不需要 cython)快速无痛


您可以在 SO 上创建一个新问题并在此处使用指向它的链接发表评论。
V
Vishvajit Pathak

首先安装驱动

pip install MySQL-python   

然后一个基本的代码是这样的:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 

H
Hasib Kamal Chowdhury

首先安装驱动程序(Ubuntu)

sudo apt-get 安装 python-pip

sudo pip install -U pip

sudo apt-get install python-dev libmysqlclient-dev

sudo apt-get 安装 MySQL-python

MySQL数据库连接代码

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

S
Suraj Rao

首先,从 https://dev.mysql.com/downloads/connector/python/ 安装 python-mysql 连接器

在 Python 控制台上输入:

pip install mysql-connector-python-rf
import mysql.connector

这个问题有点太宽泛了,但这个答案似乎有点太窄了(至少在单独安装和导入模块不会做的意义上)。似乎还有 shell 和 python 混合在单个代码块中,没有任何解释或提示 wrt 什么去哪里做什么。