這篇文章主要介紹了用Python 連接MySQL 的幾種方式,大家可以根據實際情況選擇合理的連接方式,需要的朋友可以參考下
儘管很多NoSQL 數據庫近幾年大放異彩異彩,但是像MySQL 這樣的關係型資料庫依然是網路的主流資料庫之一,每個學Python 的都有必要學好一門資料庫,不管你是做資料分析,還是網路爬蟲,Web 開發、也或機器學習,你都離不開要和資料庫打交道,而MySQL 又是最受歡迎的一種資料庫,這篇文章介紹Python 操作MySQL 的幾種方式,你可以在實際開發過程中根據實際情況合理選擇。
1、MySQL-python
#MySQL-python 又叫MySQLdb,是Python 連結MySQL 最受歡迎的一個驅動,很多框架都也是基於此庫進行開發,遺憾的是它只支援Python2.x,而且安裝的時候有很多前置條件,因為它是基於C開發的庫,在Windows 平台安裝非常不友好,經常出現失敗的情況,現在基本上不建議使用,取代的是它的衍生版本。
# 前置条件 sudo apt-get install python-dev libmysqlclient-dev # Ubuntu sudo yum install python-devel mysql-devel # Red Hat / CentOS # 安装 pip install MySQL-python
Windows 直接透過下載exe 檔案安裝,公眾號回覆「win」取得下載連結
#!/usr/bin/python import MySQLdb db = MySQLdb.connect( host="localhost", # 主机名 user="john", # 用户名 passwd="megajonhy", # 密码 db="jonhydb") # 数据库名称 # 查询前,必须先获取游标 cur = db.cursor() # 执行的都是原生SQL语句 cur.execute("SELECT * FROM YOUR_TABLE_NAME") for row in cur.fetchall(): print(row[0]) db.close()
2、mysqlclient
由於MySQL-python 年久失修,後來出現了它的Fork 版本mysqlclient,完全相容於MySQLdb,同時支援Python3 .x,是Django ORM的依賴工具,如果你想使用原生SQL 來操作資料庫,那麼推薦此驅動程式。安裝方式和 MySQLdb 是一樣的,Windows 可以在 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 網站找到 對應版本的 whl 套件下載安裝。
# Windows安装 pip install some-package.whl # linux 前置条件 sudo apt-get install python3-dev # debian / Ubuntu sudo yum install python3-devel # Red Hat / CentOS brew install mysql-connector-c # macOS (Homebrew) pip install mysqlclient
3、PyMySQL
#PyMySQL是純Python 實現的驅動,速度上比不上MySQLdb,最大的特點可能就是它的安裝方式沒那麼繁瑣,同時也相容於MySQL-pythonpip install PyMySQL # 为了兼容mysqldb,只需要加入 pymysql.install_as_MySQLdb()#一個範例
import pymysql conn = pymysql.connect(host='127.0.0.1', user='root', passwd="xxx", db='mysql') cur = conn.cursor() cur.execute("SELECT Host,User FROM user") for r in cur: print(r) cur.close() conn.close()
#4、peewee
寫原生SQL 的過程非常繁瑣,程式碼重複,沒有物件導向思維,接著誕生了許多封裝wrapper 套件和ORM 框架,ORM 是Python 物件與資料庫關係表的一種映射關係,有了ORM 你不再需要寫SQL 語句。提高了寫程式碼的速度,同時相容於多種資料庫系統,如sqlite, mysql、postgresql,付出的代價可能就是效能上的一些損失。如果你對 Django 自帶的 ORM 熟悉的話,那麼 peewee的學習成本幾乎為零。它是 Python 中是最受歡迎的 ORM 框架。pip install peewee
#
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)官方文件: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 = 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()
現在差不多搞明白了這幾種資料庫驅動的優劣,接下來你就可以選擇其中的一個進行系統的學習再把它應用到專案中去了,祝你學習開心,不懂的可以諮詢我哈。
相關推薦:
以上是用 Python 連接 MySQL 的幾種方式詳解_python的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1
好用且免費的程式碼編輯器

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器