1 - 设定
在执行任何操作之前,必须安装 MySQL 驱动程序。与 PHP 不同,默认情况下,Python 仅安装 SQLite 驱动程序。最常用的软件包是MySQLdb,但是很难使用 easy_install 进行安装。请注意,MySQLdb 仅支持 Python 2。
对于 Windows 用户,您可以获取MySQLdb的exe 。
对于 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()
Oracle(MySQL)现在支持纯 Python 连接器。这意味着无需安装任何二进制文件:它只是一个 Python 库。它称为 “连接器 / Python”。
如果您不需要 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()
如果要避免安装 mysql 标头只是为了从 python 访问 mysql,请停止使用 MySQLDb。
使用pymysql 。它可以完成 MySQLDb 的所有工作,但是它完全是在 Python 中实现的, 没有外部依赖项 。这使所有操作系统上的安装过程一致且容易。 pymysql
是 MySQLDb 和 IMHO 的替代品,没有理由将 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 ()
作为数据库驱动程序,还有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 上本地运行。
与 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 是一个不错的选择,正如其他答案中已经提到的那样。
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()
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()
在终端中运行以下命令以安装 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 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
有关更多命令: https : //www.w3schools.com/python/python_mysql_getstarted.asp