繁体   English   中英

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

[英]How do I connect to a MySQL Database in Python?

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

三步用Python 2连接MYSQL

1 - 设置

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

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

对于 Linux,这是一个临时包 (python-mysqldb)。 (您可以在sudo apt-get install 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 ) 之外,什么都不需要。

这是使用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()

参考这里

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

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

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

安装后,您可以在这里看到一些使用示例

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

使用pymysql 它完成 MySQLDb 所做的所有事情,但它纯粹是用 Python 实现的,没有外部依赖关系 这使得所有操作系统上的安装过程一致且简单。 pymysqlpymysql替代品,恕我直言,没有理由将 MySQLDb 用于任何事情......永远! - PTSD from installing MySQLDb on Mac OSX and *Nix systems ,但这只是我。

安装

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

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

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

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

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

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

作为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 上本地运行。

那么如何用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 是一个不错的选择。

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

pip install mysql-connector-python

并在您的 python 编辑器中运行它以连接到 MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      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 or update

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

Sqlalchemy


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

安装

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

尽管上面有所有答案,但如果您不想预先连接到特定的数据库,例如,如果您仍然想创建数据库 (!),您可以使用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()

从 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. 使用 mysql 连接器 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 连接器 Python 的重要 API

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

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

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

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

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

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

我的首选方法也是 pythonic,是使用强大的SQLAlchemy 这里是查询相关教程,这里是 SQLALchemy 的ORM 功能教程。

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

这是 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

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

记住! 它区分大小写。

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

也看看风暴 它是一个简单的 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

有关更多信息,请参阅教程

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

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

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

cursor = db.cursor()

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

对于python 3.3

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

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

(你不需要cython)快速无痛

首先安装驱动

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 

首先安装驱动程序(Ubuntu)

  • 须藤 apt-get 安装 python-pip

  • 须藤 pip install -U pip

  • sudo apt-get install python-dev libmysqlclient-dev

  • 须藤 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 ()

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

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

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

conn = mysql.connector.connect(host= you host name like localhost or 127.0.0.1 , username= your username like root , password = your 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()

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

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

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

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

如果您只想从数据库中绘制一些数据,另一种选择是使用 Jupyter内核,它是为 MariaDB 设计的,但它也应该很容易在 MySQL 上工作。

Python does not come with an inbuilt Library to interact with MySQL, so in order to make a connection between the MySQL database and Python we need to install the MySQL driver or module for our Python Environment.

pip install mysql-connector-python

mysql-connecter-python 是一个开源 Python 库,可以通过几行代码将您的 python 代码连接到 MySQL 数据库。 并且与最新版本的Python非常兼容。

安装 mysql-connector-python 后,您可以使用以下代码片段连接到 MySQL 数据库。

import mysql.connector

Hostname = "localhost"
Username = "root"
Password ="admin"   #enter your MySQL password
 
#set connection
set_db_conn = mysql.connector.connect(host= Hostname, user=Username, password=Password)

if set_db_conn:
    print("The Connection between has been set and the Connection ID is:")
    #show connection id
    print(set_db_conn.connection_id)

将 Django 与 MySQL 连接

在 Django 中,要将您的 model 或项目连接到 MySQL 数据库,您需要安装 mysqlclient 库。

pip install mysqlclient

要配置您的 Django 设置,以便您的项目可以连接到 MySQL 数据库,您可以使用以下设置。

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'database_name',
            'USER': 'username',
            'PASSWORD': 'databasepassword@123',
            'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
            'PORT': '3306',
            }

我在我的博客上编写了专门的 Python 教程,其中介绍了如何连接到 MySQL 数据库并使用 Python 创建表。 要了解更多信息, 请单击此处

这就是我所做的,如果数据库还不存在,它会为你创建:

import sqlite3

conn = sqlite3.connect('data.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS usersdata(idpedido INTEGER PRIMARY KEY ,cliente TEXT ,telefone TEXT ,prioridade TEXT ,data_entrada DATE ,data_prevista DATE ,horario_entrada TEXT , horario_saida TEXT , status TEXT)')


def add_data(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status):
    c.execute('INSERT INTO usersdata(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status ) VALUES (?,?,?,?,?,?,?,?,?)',(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida, status))
    conn.commit()

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

在 Python 控制台上输入:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM