
來源:Python爬蟲與數(shù)據(jù)挖掘
作者: Python進(jìn)階者
大家好,我是Python進(jìn)階者。
前言
我們?cè)谶M(jìn)行Python編程的時(shí)候,時(shí)常要將一些數(shù)據(jù)保存起來,其中最方便的莫過于保存在文本文件了。但是如果保存的文件太大,用文本文件就不太現(xiàn)實(shí)了,畢竟打開都是個(gè)問題,這個(gè)時(shí)候我們需要用到數(shù)據(jù)庫(kù)。提到數(shù)據(jù)庫(kù),相信大部分人都不會(huì)陌生,今天我們要學(xué)的就是數(shù)據(jù)庫(kù)中小編自認(rèn)為最棒的Mysql數(shù)據(jù)庫(kù)了。
為了讓Python與Mysql 交互,這里我們需要用到Pymsql模塊才行。
下載模塊:
pip install pymysql
導(dǎo)入模塊:
import pymysql
打開數(shù)據(jù)庫(kù)連接軟件 SqlYong,如圖:
輸入命令:
CREATE DATABASE IF NOT EXISTS people;
這樣就創(chuàng)建了一個(gè)people 數(shù)據(jù)庫(kù)。
USE people; CREATE TABLE IF NOT EXISTS student(id INT PRIMARY KEY AUTO_INCREMENT,NAME CHAR(10) UNIQUE,score INT NOT NULL,tim DATETIME)ENGINE=INNOBASE CHARSET utf8; INSERT INTO student(NAME,score,tim)VALUES('fasd',60,'2020-06-01') SELECT * FROM student;
通過上述操作便創(chuàng)建了一個(gè)數(shù)據(jù)表Student并向其中寫入了數(shù)據(jù),結(jié)果如下:
我們可以一行代碼刪除這個(gè)插入的 數(shù)據(jù):
TRUNCATE student;
將下圖中的參數(shù)依次填入初始化參數(shù)中,
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
這樣就連接到了people數(shù)據(jù)庫(kù),可以看下連接成功的打印信息:
可以看到我們打印了Mysql的版本和Host信息。
1.創(chuàng)建游標(biāo)
cur=db.cursor
2.編寫插入數(shù)據(jù)表達(dá)式
sql="INSERT INTO student(NAME,score,tim)VALUES('任性的90后boy',100,now())"
3.開啟游標(biāo)事件
cur.begin()
4.執(zhí)行數(shù)據(jù)庫(kù)語句,異常判斷
try:
cur.execute(sql) 執(zhí)行數(shù)據(jù)庫(kù)語句
except Exception as e: print(e)
db.rollback() 發(fā)生異常進(jìn)行游標(biāo)回滾操作 else:
db.commit() 提交數(shù)據(jù)庫(kù)操作 finally:
cur.close() 關(guān)閉游標(biāo)
db.close() 關(guān)閉數(shù)據(jù)庫(kù)
5,執(zhí)行插入操作
數(shù)據(jù)庫(kù)建立好后,我們可以對(duì)它們進(jìn)行插入數(shù)據(jù)的操作。
import time
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="INSERT INTO student(NAME,score,tim) VALUES ('%s',%d,'%s')" data=('HW',90,tt) try:
cur.execute(sql%data)
except Exception as e:
print(e)
db.rollback() else:
db.commit() finally:
cur.close()
db.close()
這樣就可以將數(shù)據(jù)插入進(jìn)去了。我們還可以自定義插入:
import pymysql
import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
s=input('string:')
d=input('number:')
sql="INSERT INTO student(NAME,score,tim)VALUES('%s','%s','%s')" try:
data=(s,d,tt)
cur.execute(sql%data)
except Exception as e: print(e)
db.rollback() else:
db.commit()
finally:
cur.close()
db.close()
另外,我們也可以同時(shí)插入多條數(shù)據(jù),只需先定義好所有的數(shù)據(jù),然后在調(diào)用即可,這里需要用到插入多條數(shù)據(jù)的函數(shù)Executemany,在這里我插入十萬條數(shù)據(jù),并測(cè)試插入時(shí)間,步驟如下:
import pymysql
import time start=time.time()
tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin() sql="insert into student(NAME,score,tim)values(%s,%s,%s)" def get():
ab=[] for y in range(1,100000): if y>=100: data=('user-'+str(y),str(str(float('%.f'%(y%100)))),tt) else: data=('user-'+str(y),str(y),tt)
ab.append(data) return ab
try: data=get()
cur.executemany(sql,data) except Exception as e:
print(e)
db.rollback() else:
db.commit()
finally:
print('插入數(shù)據(jù)完畢')
cur.close()
db.close() end=time.time()
print('用時(shí):',str(end-start))
6.執(zhí)行更新操作
有些數(shù)據(jù)我們覺得它過時(shí)了,想更改,就要更新它的數(shù)據(jù)。
import time
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="update student set name='zjj' where score=100 " 當(dāng)分?jǐn)?shù)是100分的時(shí)候?qū)⒚指臑閦jj try:
cur.execute(sql%data) except Exception as e:
print(e)
db.rollback() else:
db.commit() finally:
cur.close()
db.close()
7.執(zhí)行刪除操作
有時(shí)候一些數(shù)據(jù)如果對(duì)于我們來說沒有任何作用了的話了,我們就可以將它刪除了,不過這里是刪除數(shù)據(jù)表中的一條記錄。
import pymysql
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="delete from student where name='fasd';" 當(dāng)名字等于‘fasd’的時(shí)候刪除這個(gè)記錄 try:
cur.execute(sql) except Exception as e:
print(e)
db.rollback() else:
db.commit() finally:
cur.close()
db.close()
你也可以刪除表中所有的數(shù)據(jù),只需將Sql語句改為:
sql='TRUNCATE student;'
當(dāng)然你也可以刪除表,但是一般不建議這樣做,以免誤刪:
DROP TABLE IF EXISTS student;
8.執(zhí)行查詢操作
有時(shí)候我們需要對(duì)數(shù)據(jù)庫(kù)中的數(shù)據(jù)進(jìn)行查詢,Python也能輕松幫我們搞定。
import pymysql
import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="select * from student;" try:
cur.execute(sql)
res=cur.fetchall() 查詢數(shù)據(jù)庫(kù)中的數(shù)據(jù) for y in res: print(y) 打印數(shù)據(jù)庫(kù)中標(biāo)的所有數(shù)據(jù),以元祖的形式
except Exception as e: print(e)
db.rollback() else:
db.commit()
finally:
cur.close()
db.close()
在我們進(jìn)行網(wǎng)絡(luò)爬蟲的時(shí)候,需要保存大量數(shù)據(jù),這個(gè)時(shí)候數(shù)據(jù)庫(kù)就派上用場(chǎng)了,可以更方便而且更快捷保存數(shù)據(jù)。
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫(kù)管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫(kù)表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動(dòng)態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價(jià)值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫(kù)表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫(kù))處理 Excel 數(shù)據(jù)時(shí),“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場(chǎng)景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對(duì)象的 text 與 content:區(qū)別、場(chǎng)景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請(qǐng)求開發(fā)時(shí)(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價(jià)值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫(kù)表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請(qǐng)求工具對(duì)比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請(qǐng)求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)時(shí)的科學(xué)計(jì)數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價(jià)值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營(yíng)問題、提升執(zhí)行效率的核心手段,其價(jià)值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營(yíng)銷案例:數(shù)據(jù)驅(qū)動(dòng)下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營(yíng)銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價(jià)值 在數(shù)據(jù)驅(qū)動(dòng)決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實(shí)踐到業(yè)務(wù)價(jià)值挖掘 在數(shù)據(jù)分析場(chǎng)景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計(jì)模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價(jià)值導(dǎo)向 統(tǒng)計(jì)模型作為數(shù)據(jù)分析的核心工具,并非簡(jiǎn)單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10