如何使用 python 程序连接到 MySQL 数据库?
pymysql
因为它是根据 this comparison 的纯免费 Python。
三步使用 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
) 外,没有其他要求。
这是使用仅支持 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()
如果您不需要 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
,那就太好了。
Oracle (MySQL) 现在支持纯 Python 连接器。这意味着无需安装二进制文件:它只是一个 Python 库。它被称为“连接器/Python”。
http://dev.mysql.com/downloads/connector/python/
安装后可以看到一些使用示例here
如果您想避免安装 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。
尝试使用 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 ()
在终端中运行此命令以安装 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()
对于较新版本的 Python (>=3.6)
使用 mysqlclient 或 pymysql(推荐)。
对于旧版本的 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 是一个不错的选择,正如其他答案中已经提到的那样。
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()
从 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) 来获取数据
尽管有上述所有答案,但如果您不想预先连接到特定数据库,例如,如果您仍想创建数据库 (!),您可以使用 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()
尽管你们中的一些人可能会将其标记为重复并且对我复制别人的答案感到不安,但我真的很想强调 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
MySQLdb 是直接的方式。您可以通过连接执行 SQL 查询。时期。
我的首选方式(也是 pythonic)是使用强大的 SQLAlchemy 代替。这是一个 query related 教程,这是一个关于 SQLALchemy 的 ORM capabilities 的教程。
对于 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 快得多
只是对上述答案的修改。只需运行此命令即可为 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
mysql.connector
和 _mysql
都给出了导入错误(尽管第二个选项应该根据文档工作)。 import MySQLdb
有效,然后 MySQLdb.connect...
另请查看 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。
这是 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')
获取库的第一步:打开终端并执行 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 =
数据库名称)
不要删除主机、用户名、密码等其他信息。
对于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)
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 ()
首先,从 https://dev.mysql.com/downloads/connector/python/ 安装 python-mysql 连接器
在 Python 控制台上输入:
pip install mysql-connector-python-rf
import mysql.connector
不定期副业成功案例分享