1、MySQLdb
MySQLdb又叫MySQL-python ,是 Python 連接 MySQL 最流行的一個(gè)驅(qū)動,很多框架都也是基于此庫進(jìn)行開發(fā),遺憾的是它只支持 Python2.x,而且安裝的時(shí)候有很多前置條件,因?yàn)樗腔贑開發(fā)的庫,在 Windows 平臺安裝非常不友好,經(jīng)常出現(xiàn)失敗的情況,現(xiàn)在基本不推薦使用,取代的是它的衍生版本。
# 前置條件sudo apt-get install python-dev libmysqlclient-dev # Ubuntusudo yum install python-devel mysql-devel # Red Hat / CentOS
# 安裝pip install MySQL-pythonWindows 直接通過下載 exe 文件安裝
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(
host="localhost", # 主機(jī)名
user="root", # 用戶名
passwd="pythontab.com", # 密碼
db="testdb") # 數(shù)據(jù)庫名稱
# 查詢前,必須先獲取游標(biāo)
cur = db.cursor()
# 執(zhí)行的都是原生SQL語句
cur.execute("SELECT * FROM mytable")for row in cur.fetchall():
print(row[0])
db.close()
2、mysqlclient
由于 MySQL-python(MySQLdb) 年久失修,后來出現(xiàn)了它的 Fork 版本 mysqlclient,完全兼容 MySQLdb,同時(shí)支持 Python3.x,是 Django ORM的依賴工具,如果你想使用原生 SQL 來操作數(shù)據(jù)庫,那么推薦此驅(qū)動。安裝方式和 MySQLdb 是一樣的,Windows 可以在 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 網(wǎng)站找到 對應(yīng)版本的 whl 包下載安裝。
pip install mysqlclient
3、PyMySQL
PyMySQL 是純 Python 實(shí)現(xiàn)的驅(qū)動,速度上比不上 MySQLdb,最大的特點(diǎn)可能就是它的安裝方式?jīng)]那么繁瑣,同時(shí)也兼容 MySQL-python
pip install PyMySQL# 為了兼容mysqldb,只需要加入pymysql.install_as_MySQLdb()
例子:
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd="pythontab.com", db='testdb')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")for r in cur:
print(r)
cur.close()conn.close()
還有一種常用的鏈接設(shè)置
import pymysql
pymysql.install_as_MySQLdb() # 讓使用mysqldb的框架兼容pymysql
from sqlalchemy import create_engine
# 通過pandas.read_sql_query讀取mysql數(shù)據(jù),其中需要設(shè)置參數(shù)engine,有pymysql.connet和sqlalchemy.create_engine兩種
#create_engine('dialect+driver://username:password@host:port/database?charset=utf8')
engine = create_engine('mysql+pymysql://frogdata001:Frogdata!123@106.13.128.83:3306/adventure_ods?charset=utf8')
gather_customer_order=pd.read_sql_query(# read_sql_query只能用過SQL語句進(jìn)行查詢
sql='select * from dw_customer_order',
con=engine
)
4、peewee
寫原生 SQL 的過程非常繁瑣,代碼重復(fù),沒有面向?qū)ο笏季S,繼而誕生了很多封裝 wrapper 包和 ORM 框架,ORM 是 Python 對象與數(shù)據(jù)庫關(guān)系表的一種映射關(guān)系,有了 ORM 你不再需要寫 SQL 語句。提高了寫代碼的速度,同時(shí)兼容多種數(shù)據(jù)庫系統(tǒng),如sqlite, mysql、postgresql,付出的代價(jià)可能就是性能上的一些損失。如果你對 Django 自帶的 ORM 熟悉的話,那么 peewee的學(xué)習(xí)成本幾乎為零。它是 Python 中是最流行的 ORM 框架。
安裝
pip install peewee
例子:
import peeweefrom peewee
import *db = MySQLDatabase('testdb', user='root', passwd='pythontab.com')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = dbBook.create_table()book = Book(author="pythontab", title='pythontab is good website')
book.save()for book in Book.filter(author="pythontab"):
print(book.title)
官方文檔:http://docs.peewee-orm.com/en/latest/peewee/installation.html
5、SQLAlchemy
如果想找一種既支持原生 SQL,又支持 ORM 的工具,那么 SQLAlchemy 是最好的選擇,它非常接近 Java 中的 Hibernate 框架。
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Address, Base, Person
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street_name = Column(String(250))
engine = create_engine('sqlite:///sqlalchemy_example.db')Base.metadata.bind = engineDBSession = sessionmaker(bind=engine)
session = DBSession()
# Insert a Person in the person
tablenew_person = Person(name='new person')session.add(new_person)session.commit()