Python連接MySQL的幾種方式

目前,常見的Python連接MySQL主要有以下幾種方式:SQLAlchemy,PyMySQL,peewee,MySQLdb(只支持Python2.x,已基本廢棄)MySQLclient等,下面我們分別做相應(yīng)介紹。

1、PyMySQL
安裝方式簡(jiǎn)單,同時(shí)也兼容 MySQL-python,功能強(qiáng)大,它的運(yùn)行原理如下圖所示:


image.png

實(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è)贊吧,謝謝你的支持,?( ′???` )?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容