目前凫岖,常見的Python連接MySQL主要有以下幾種方式:SQLAlchemy,PyMySQL晒哄,peewee购啄,MySQLdb(只支持Python2.x襟企,已基本廢棄)MySQLclient等,下面我們分別做相應(yīng)介紹狮含。
1顽悼、PyMySQL
安裝方式簡單,同時(shí)也兼容 MySQL-python几迄,功能強(qiáng)大表蝙,它的運(yùn)行原理如下圖所示:
實(shí)現(xiàn)代碼:
import pymysql
pip install PyMySQL
# 為了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()
# 打開數(shù)據(jù)庫連接
conn = pymysql.connect(host='*.*.*.*',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = conn.cursor()
# 使用 execute() 方法執(zhí)行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法獲取單條數(shù)據(jù);使用 fetchall() 方法獲取所有數(shù)據(jù)
data = cursor.fetchall()
for item in data:
print(item[0])
# 關(guān)閉數(shù)據(jù)庫連接
cursor.close()
2乓旗、SQLAlchemy
sqlalchemy是python的orm程序府蛇,(object relational mapping,對(duì)象映射關(guān)系程序)在使用sqlalchemy之前要先給python安裝mysql驅(qū)動(dòng)
它既支持原生SQL又支持ORM
實(shí)現(xiàn)代碼:
create_engine("數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動(dòng)://數(shù)據(jù)庫用戶名:數(shù)據(jù)庫密碼@IP地址:端口/數(shù)據(jù)庫",其他參數(shù))
echo=True是開啟調(diào)試屿愚,這樣當(dāng)我們執(zhí)行文件的時(shí)候會(huì)提示相應(yīng)的文字汇跨。
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 = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Insert a Person in the person table
new_person = Person(name='new person')
session.add(new_person)
session.commit()
3务荆、 MySQL-python
因?yàn)樗患嫒軵ython3.x,所以現(xiàn)在已經(jīng)被MySQLclient取代
# _*_ coding: utf-8 _*_
import MySQLdb
# 創(chuàng)建連接
conn = MySQLdb.connect(
host='10.181.68.153',# 你的MySQL服務(wù)器地址
port=3357,# 端口
user='root',# 訪問數(shù)據(jù)庫服務(wù)的用戶名和密碼
passwd='Xb123456@',
db='xiaob_new',# 數(shù)據(jù)庫名稱
charset='utf8' # 如果去掉這句話穷遂,下面的一等獎(jiǎng)會(huì)展示亂碼
)
# 執(zhí)行查詢
cur = conn.cursor()
cur.execute("select * from award") # 執(zhí)行查詢
results = cur.fetchall() # 拿到返回結(jié)果
for re in results: # 循環(huán)并打印拿到的結(jié)果
print(re)
4函匕、peewee
(來自網(wǎng)絡(luò))寫原生 SQL 的過程非常繁瑣,代碼重復(fù)蚪黑,沒有面向?qū)ο笏季S盅惜,繼而誕生了很多封裝 wrapper 包和 ORM 框架,ORM 是 Python 對(duì)象與數(shù)據(jù)庫關(guān)系表的一種映射關(guān)系忌穿,有了 ORM 你不再需要寫 SQL 語句抒寂。提高了寫代碼的速度,同時(shí)兼容多種數(shù)據(jù)庫系統(tǒng)掠剑,如sqlite, mysql屈芜、postgresql,付出的代價(jià)可能就是性能上的一些損失朴译。如果你對(duì) Django 自帶的 ORM 熟悉的話井佑,那么 peewee的學(xué)習(xí)成本幾乎為零。它是 Python 中是最流行的 ORM 框架眠寿。
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)
如果覺得有用請(qǐng)給我點(diǎn)個(gè)贊吧躬翁,謝謝你的支持,?( ′???` )?