Python 操作 MySQL 的5種方式(轉)

Python 操作 MySQL 的5種方式

不管你是做數據分析,還是網絡爬蟲,Web 開發、亦或是機器學習,你都離不開要和數據庫打交道,而 MySQL 又是最流行的一種數據庫,這篇文章介紹 Python 操作 MySQL 的5種方式,你可以在實際開發過程中根據實際情況合理選擇。

?

1、MySQLdb

MySQLdb又叫MySQL-python ,是 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 文件安裝
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost",    # 主機名user="root",         # 用戶名passwd="pythontab.com",  # 密碼db="testdb")        # 數據庫名稱
# 查詢前,必須先獲取游標
cur = db.cursor()
# 執行的都是原生SQL語句
cur.execute("SELECT * FROM mytable")
for row in cur.fetchall():print(row[0])
db.close()

?


2、mysqlclient

由于 MySQL-python(MySQLdb) 年久失修,后來出現了它的 Fork 版本 mysqlclient,完全兼容 MySQLdb,同時支持 Python3.x,是 Django ORM的依賴工具,如果你想使用原生 SQL 來操作數據庫,那么推薦此驅動。安裝方式和 MySQLdb 是一樣的,Windows 可以在 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 網站找到 對應版本的 whl 包下載安裝。

?

pip install mysqlclient

?

3、PyMySQL

PyMySQL 是純 Python 實現的驅動,速度上比不上 MySQLdb,最大的特點可能就是它的安裝方式沒那么繁瑣,同時也兼容 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()

?

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('testdb', user='root', passwd='pythontab.com')
class Book(peewee.Model):author = peewee.CharField()title = peewee.TextField()class Meta:database = db
Book.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 = 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()

?

?

轉載于:https://www.cnblogs.com/yhleng/p/9798907.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388212.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388212.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388212.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

unity3d 人員控制代碼

普通瀏覽復制代碼private var walkSpeed : float 1.0;private var gravity 100.0;private var moveDirection : Vector3 Vector3.zero;private var charController : CharacterController;function Start(){charController GetComponent(CharacterController);animation.w…

刪除wallet里面登機牌_登機牌丟失問題

刪除wallet里面登機牌On a sold-out flight, 100 people line up to board the plane. The first passenger in the line has lost his boarding pass but was allowed in regardless. He takes a random seat. Each subsequent passenger takes their assigned seat if availa…

PHP 備份還原 MySql 數據庫

原生 PHP 備份還原 MySql 數據庫 支持 MySql,PDO 兩種方式備份還原 php5.5 以上的版本建議開啟pdo擴展,使用 pdo 備份還原數據 備份文件夾 db_backup、import/log 文件要有讀寫權限環境版本 本人測試環境 php:5.5.38 /5.6.27-nts/7.0.12-nts; mysql: 5.5…

Java? 教程(Queue接口)

Queue接口 Queue是在處理之前保存元素的集合&#xff0c;除了基本的Collection操作外&#xff0c;隊列還提供額外的插入、刪除和檢查操作&#xff0c;Queue接口如下。 public interface Queue<E> extends Collection<E> {E element();boolean offer(E e);E peek();…

字符串操作截取后面的字符串_對字符串的5個必知的熊貓操作

字符串操作截取后面的字符串We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require preprocessing to con…

最新 Unity3D鼠標滑輪控制物體放大縮小 [

var s 1.0;function Update () {var cube GameObject.Find("Cube");if(Input.GetAxis("Mouse ScrollWheel")){s Input.GetAxis("Mouse ScrollWheel");cube.transform.localScaleVector3(1*s,1*s,1*s);}}

sublime-text3 安裝 emmet 插件

下載sublime&#xff0c;http://www.sublimetext.com/ 安裝package control &#xff1a;https://packagecontrol.io/ins... 這個地址需要翻墻&#xff0c;訪問不了的可以看下圖 import urllib.request,os,hashlib; h 6f4c264a24d933ce70df5dedcf1dcaee ebe013ee18cced0ef93d…

數據科學家訪談錄 百度網盤_您應該在數據科學訪談中向THEM提問。

數據科學家訪談錄 百度網盤A quick search on Medium with the keywords “Data Science Interview” resulted in hundreds of Medium articles to help guide the reader from what concepts are covered to even specific company interviews ranging from Tesla, Walmart, …

unity3d]鼠標點擊地面人物自動走動(也包含按鍵wasdspace控制)

目錄(?)[-] 一效果圖二大概步驟 創建一個plane設置層為Terrain因為后面要判斷是否點擊的是這個層準備好人物模型并且將三個腳本拖放到人物上并且將動畫文件也拖放好記得看前面提醒哦 ThirdPersonCamera相當于smoothflowThirdPersonController修改版mouseMoveContr鼠標點擊人物…

uva 524(Prime Ring Problem UVA - 524 )

dfs練習題,我素數打表的時候ji了&#xff0c;一直沒發現實際上是ji*i&#xff0c;以后可記住了。還有最后一行不能有空格。。。昏迷了半天 我的代碼(紫書上的算法) #include <bits/stdc.h> using namespace std; int bk[110]; int num[110]; int vis[110]; int n; void d…

Web 開發基礎

一、 Web 開發簡介 最早的軟件都是運行在大型機上的&#xff0c;軟件使用者登陸到大型機上去運行軟件。后來隨著 PC 機的興起&#xff0c;軟件開始主要運行在桌面上&#xff0c;而數據庫這樣的軟件運行在服務器端&#xff0c;這種 Client/Server 模式簡稱 CS 架構。隨著互聯網的…

power bi函數_在Power BI中的行上使用聚合函數

power bi函數Aggregate functions are one of the main building blocks in Power BI. Being used explicitly in measures, or implicitly defined by Power BI, there is no single Power BI report which doesn’t use some sort of aggregate functions.聚合功能是Power BI…

關于如何在Python中使用靜態、類或抽象方法的權威指南

Python中方法的工作方式 方法是存儲在類屬性中的函數&#xff0c;你可以用下面這種方式聲明和訪問一個函數 >>> class Pizza(object):... def __init__(self, size):... self.size size... def get_size(self):... return self.size...>&…

廣義估計方程估計方法_廣義估計方程簡介

廣義估計方程估計方法A key assumption underpinning generalized linear models (which linear regression is a type of) is the independence of observations. In longitudinal data this will simply not hold. Observations within an individual (between time points) …

css二

結構性偽類:nth-child(index)系列1.:first-child2.:last-child3.nth-last-child(index)4.only-child :nth-of-type(index)系列1.first-of-type2.last-of-type3.nth-last-type(index)4.only-of-type :not偽類處理導航欄最后一個豎劃線a:not(:last-of-type) :empty偽類 選中所有內…

Unity3d鼠標點擊屏幕來控制人物的走動

今天呢&#xff0c;我們來一起實現一個在RPG中游戲中十分常見的功能&#xff0c;通過鼠標點擊屏幕來控制人物的走動。首先來說一下原理&#xff0c;當我們點擊屏幕時&#xff0c;我們按照一定的方法&#xff0c;將屏幕上的二維坐標轉化為三維坐標&#xff0c;然后我們從攝像機位…

Java中的ReentrantLock和synchronized兩種鎖定機制的對比

2019獨角獸企業重金招聘Python工程師標準>>> 多線程和并發性并不是什么新內容&#xff0c;但是 Java 語言設計中的創新之一就是&#xff0c;它是第一個直接把跨平臺線程模型和正規的內存模型集成到語言中的主流語言。核心類庫包含一個 Thread 類&#xff0c;可以用它…

10.15 lzxkj

幾天前寫的&#xff0c;忘了放了&#xff0c;在此填坑 10月16的題我出的不寫題解了 lzxkj 題目背景 眾所不周知的是&#xff0c; 酒店之王 xkj 一個經常迷失自我的人 有一天&#xff0c; 當起床鈴再一次打響的時候&#xff0c; TA 用 O(1)的時間在 TA 那早就已經生銹的大腦中自…

大數定理 中心極限定理_中心極限定理:直觀的遍歷

大數定理 中心極限定理One of the most beautiful concepts in statistics and probability is Central Limit Theorem,people often face difficulties in getting a clear understanding of this and the related concepts, I myself struggled understanding this during my…

萬惡之源 - Python數據類型二

列表 列表的介紹 列表是python的基礎數據類型之一 ,其他編程語言也有類似的數據類型. 比如JS中的數 組, java中的數組等等. 它是以[ ]括起來, 每個元素用 , 隔開而且可以存放各種數據類型: lst [1,a,True,[2,3,4]]列表相比于字符串,不僅可以存放不同的數據類型.而且可…