如何使用Python连接MySQL数据库?

1117 python mysql

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

e-s*_*tis 1227

使用Python以3个步骤连接到MYSQL

1 - 设置

您必须在执行任何操作之前安装MySQL驱动程序.与PHP不同,默认情况下只使用Python安装SQLite驱动程序.最常用的包是MySQLdb,但使用easy_install很难安装它.

对于Windows用户,您可以获得MySQLdbexe.

对于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()
Run Code Online (Sandbox Code Playgroud)

当然,有数千种可能性和选择; 这是一个非常基本的例子.您将不得不查看文档.一个很好的起点.

3 - 更高级的用法

一旦你知道它是如何工作的,你可能想要使用ORM来避免手动编写SQL并操纵你的表,因为它们是Python对象.SQL社区中最着名的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
Run Code Online (Sandbox Code Playgroud)

此示例开箱即用.除了使用peewee(pip install peewee)之外别无其他.

  • 很高兴你喜欢小便!! 我已经添加了对MySQL的支持以及与它集成的一些[文档](http://charlesleifer.com/docs/peewee/peewee/uses.html#using-with-mysql).快乐的黑客! (44认同)
  • 请注意,在撰写本文时,MySQLdb不支持Python 3. sourceforge页面显示"即将推出Python 3支持",但自2012-10-08以来尚未更新.对于Python 3,有[PyMySQL](https://github.com/petehunt/PyMySQL/)和[oursql](http://pythonhosted.org/oursql/index.html). (14认同)
  • 另请注意以下内容是必需的:`pip install MySQL-python` (8认同)
  • 对于非标准端口上的外部服务器的示例连接,此答案将更有帮助,以显示如何执行此操作.说localhost是通常的方法,这是无稽之谈. (5认同)
  • Peewee已更改默认行为,并且默认情况下不再使用自动提交.即使数据库驱动程序的情况现在已经改变 这个问题需要更新,但由于对我的一些答案滥用了编辑,我不再编辑它们了. (3认同)
  • 停止使用 MySqlDB。保存您的理智并使用 pymysql 它是纯 python 。检查我的回复中的示例,......不客气:) - http://stackoverflow.com/a/34503728/751528 (2认同)
  • 请注意,截至目前,它的exe文件仅支持2.7版本的Python版本. (2认同)

Geo*_*ker 181

这是一种方法:

#!/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()
Run Code Online (Sandbox Code Playgroud)

参考这里

  • 您是否需要在此示例中提交,因为您没有修改数据库? (4认同)
  • 注意 - 此模块在连接时没有时区支持 (3认同)

小智 120

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

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

  • 是的.此外,它比MySQLdb更麻烦,我认为API更好.这应该是答案. (8认同)
  • @ComFreek很棒.怎么样更好?我们可以停止应用"Windows工作流程".包管理存在. (6认同)
  • @ J0hnG4lt您只需点击登录表单下方的"不,谢谢,只需开始下载"(实际上似乎是强制性的,但不是). (2认同)

Mr.*_*pik 114

如果你不需要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()
Run Code Online (Sandbox Code Playgroud)

  • `pip install mysql-connector-python`也可以.我不知道它在PyPi上不再支持的地方了吗?如果您无法访问系统上的gcc/C编译器,那就太棒了,因此无法安装`mysqldb`. (7认同)
  • 截至2016年11月7日,pip的包只是mysql-connector,```pip search mysql-connector```来查找包名.从这里回答:http://stackoverflow.com/a/22829966/2048266 (7认同)
  • 不像你声称的那么简单.当我尝试安装rpm时,我的RPM中出现了一些依赖性问题(FileDigests和PayloadIsXz):`rpm -i mysql-connector-python-1.1.5-1.el6.noarch.rpm``错误:失败的依赖项:``rpmlib(FileDigests)<= 4.6.0-1需要mysql-connector-python-1.1.5-1.el6.noarch``rpmlib(PayloadIsXz)<= 5.2-1是mysql-connector-需要的蟒蛇,1.1.5-1.el6.noarch` (2认同)
  • 我以前更喜欢这个库,但PyPi不再正式支持它.我已经搬到了MySQLdb. (2认同)
  • @Arms:PyPi上不再正式支持?你有这方面的资料吗? (2认同)

Oke*_*ieE 110

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

使用pymysql.它完成了MySQLDb的所有功能,但它完全是在没有外部依赖性的 Python中实现的.这使得所有操作系统上的安装过程一致且简单. 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()
Run Code Online (Sandbox Code Playgroud)

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

如果你有使用MySQLdb的现有代码,你可以使用这个简单的过程轻松地用pymysql替换它:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
Run Code Online (Sandbox Code Playgroud)

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

  • 不,我认为它根本不强.鉴于可以选择使用MySQLDb或PyMysql,我认为选择PyMysql是没有道理的,因为它是一个没有依赖关系的简单pip安装,而MySQLDb需要为你的OS平台安装mysql开发头文件才能工作.Sqlalchemy没有考虑到这一点,因为它仍然需要包装一个可以与神秘文件交谈的模块,如PyMysql,MySQLDb,CyMySQL等Peewee看起来很有趣,我会检查出来的 (4认同)
  • "总是"有点强烈...... peewee或sqlalchemy有什么问题?即使它们确实作为ORM库存在,它们仍然同样有用 (3认同)
  • @ cricket_007 peewee和sqlalchemly没有实现自己的db连接器,它们在MySQLdb等上面提供了一个层. (2认同)

Hor*_*ude 23

尝试使用MySQLdb

这里有一个页面: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 ()
Run Code Online (Sandbox Code Playgroud)

  • 注意 - 此模块在连接时没有时区支持 (2认同)

boo*_*dev 18

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

  • 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]
Run Code Online (Sandbox Code Playgroud)

文档中教程相当不错.

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

  • 我不明白'在python 3.x上本地运行'.我只是尝试安装它和setup.py炸弹,因为它甚至没有使用Python 3兼容的打印调用.听起来很棒,直到我真的尝试过. (3认同)

ana*_*thi 12

SQLAlchemy的


SQLAlchemy是Python SQL工具包和Object Relational Mapper,它为应用程序开发人员提供了SQL的全部功能和灵活性.SQLAlchemy提供了一整套众所周知的企业级持久性模式,专为高效和高性能的数据库访问而设计,适用于简单的Pythonic域语言.

安装

pip install sqlalchemy
Run Code Online (Sandbox Code Playgroud)

RAW查询

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()
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)


Mah*_*hdi 11

尽管有上述所有答案,但如果您不想提前连接到特定数据库,例如,如果您想要创建数据库(!),则可以使用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()
Run Code Online (Sandbox Code Playgroud)


Vis*_*ule 11

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

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

  1. 使用 pip 安装连接器

    pip install mysql-connector-python

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

  1. 使用connect()mysql 连接器 python 的方法连接到 MySQL。将所需的参数传递给connect()方法。即主机、用户名、密码和数据库名称。

  2. cursorconnect()方法返回的连接对象创建对象以执行 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()
Run Code Online (Sandbox Code Playgroud)

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

MySQL 连接器 Python 的重要 API

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

  • 获取数据 -cursor.execute()用于运行查询和cursor.fetchall(), cursor.fetchone(),cursor.fetchmany(SIZE)以获取数据


muh*_*huk 8

MySQLdb是直截了当的方式.您可以通过连接执行SQL查询.期.

我喜欢的方式也是pythonic,而是使用强大的SQLAlchemy.这是一个与查询相关的教程,这是一个关于SQLALchemy的ORM功能的教程.

  • 链接已失效,您能查看一下并使用正确的链接更新吗? (2认同)
  • 抱歉,截至 2020 年 6 月,您的最后两个链接仍然失效。 (2认同)

Tan*_*ark 8

尽管你们中的一些人可能会将此标记为重复,并且对我复制别人的答案感到不安,但我真的很想强调 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()
Run Code Online (Sandbox Code Playgroud)

这里重要的是Tryfinally子句。这允许与始终关闭的连接,无论代码的游标/sqlstatement 部分发生了什么。大量活动连接会导致 DBLoadNoCPU 飙升并可能导致数据库服务器崩溃。

我希望这个警告有助于节省服务器和最终的工作!:D


She*_*zod 6

在终端中运行以下命令以安装mysql连接器:

pip install mysql-connector-python
Run Code Online (Sandbox Code Playgroud)

并在python编辑器中运行此命令以连接到MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database="mydatabase"
)
Run Code Online (Sandbox Code Playgroud)

执行MySQL命令的示例(在python edior中):

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 or update
Run Code Online (Sandbox Code Playgroud)

有关更多命令:https : //www.w3schools.com/python/python_mysql_getstarted.asp

  • 有些人已经在那里回答了你的问题。您只是忘记在将值插入表后运行“mydb.commit()” (3认同)

HMS*_*HMS 5

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

sudo yum install MySQL-python
sudo apt-get install MySQL-python
Run Code Online (Sandbox Code Playgroud)

记得!它区分大小写.


kai*_*kai 5

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

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

原始SQL: select * from FOO;

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

pymysql(2.4秒):

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()
Run Code Online (Sandbox Code Playgroud)

这是pymysql配置文件: 在此处输入图片说明


mysqlclient(0.4秒)

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()
Run Code Online (Sandbox Code Playgroud)

这是mysqlclient配置文件: 在此处输入图片说明

因此,似乎mysqlclient比pymysql快得多