前提準(zhǔn)備
安裝mysql
在使用pymysql的前提就是又一個mysql數(shù)據(jù)庫,這個數(shù)據(jù)庫可以是本地數(shù)據(jù)庫也可以是遠(yuǎn)程的數(shù)據(jù)庫,
mysql的安裝這里就不再贅述了,大家可以參考其他的模塊進(jìn)行安裝
安裝pymysql
pip install pymysql
連接數(shù)據(jù)庫
import pymysql
# 連接數(shù)據(jù)庫
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306)
# 創(chuàng)建數(shù)據(jù)庫的游標(biāo)
cursor = db.cursor()
#execute()方法并執(zhí)行 SQL 語句
cursor.execute("select version()")
# 讀取第一條數(shù)據(jù)
data = cursor.fetchone()
print(data)
# 關(guān)閉連接
db.close()
# 輸出:
# ('8.0.24',)
解釋:
在連接數(shù)據(jù)的時候需要指定相應(yīng)的參數(shù)
- host 數(shù)據(jù)庫ip地址,如果是本地可以用localhost或127.0.0.1 如果是遠(yuǎn)程就需要指定正確的ip地址
- user 用戶名
- password 密碼
- port 端口號 如果不指定就默認(rèn)是3306
cursor():獲取數(shù)據(jù)庫的操作游標(biāo)
execute() 執(zhí)行SQL語句,把要進(jìn)操作的內(nèi)容寫成SQL語句,
fetchone() 讀取一條數(shù)據(jù)
close() 斷開連接,釋放資源
“select version()” sql語句的執(zhí)行結(jié)果
創(chuàng)建數(shù)據(jù)庫
import pymysql
# 連接數(shù)據(jù)庫
db = pymysql.connect(host='localhost',user='root',password='123456')
# 創(chuàng)建數(shù)據(jù)庫的游標(biāo)
cursor = db.cursor()
# 創(chuàng)建數(shù)據(jù)庫spiders
cursor.execute("create database spiders")
# 關(guān)閉連接
db.close()
創(chuàng)建數(shù)據(jù)庫命令執(zhí)行一次就可以,后面我們在創(chuàng)建的數(shù)據(jù)庫中進(jìn)行其他的操作,如果創(chuàng)建的數(shù)據(jù)已經(jīng)存在程序會報錯"Can't create database 'spiders'; database exists"
拓展:
如果在創(chuàng)建數(shù)據(jù)庫的不能確認(rèn)數(shù)據(jù)庫是否存在,但是也不想在創(chuàng)建數(shù)據(jù)庫的時候發(fā)生報錯可以使用下列語句:
create database if not exists dbname
創(chuàng)建數(shù)據(jù)表、
表必須創(chuàng)建在數(shù)據(jù)庫內(nèi),所以我們需要在連接數(shù)據(jù)庫以后,需要指定操作那個數(shù)據(jù)庫
import pymysql
# 連接數(shù)據(jù)庫
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
# 創(chuàng)建數(shù)據(jù)庫的游標(biāo)
cursor = db.cursor()
sql = "create table if not exists students(id varchar(255) not null,name varchar(255) not null,age int not null,primary key (id))"
cursor.execute(sql)
db.close()
這次的在連接mysql的時候connect
函數(shù)新增了一個參數(shù),db='spiders'
指定我們要連接的數(shù)據(jù)庫,后面創(chuàng)建的表也會創(chuàng)建到當(dāng)前數(shù)據(jù)庫。
創(chuàng)建數(shù)據(jù)庫的sql
語句是 "create table if not exists students(id varchar(255) not null,name varchar(255) not null,age int not null,primary key (id))"
創(chuàng)建的數(shù)據(jù)庫名為students
,三列 id
、name
、age
,都是非空,主鍵為id
插入數(shù)據(jù)
import pymysql
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
cursor = db.cursor()
id = '10005'
name = 'zhangsan'
age = '20'
#方式1
# sql = "insert into students(id,name,age) values('"+id+"','"+name+"','"+age+"')"
# cursor.execute(sql)
# 方式2
# sql = "insert into students(id,name,age) values('{}','{}','{}')".format(id,name,age)
# cursor.execute(sql)
# 方式3(推薦)
sql = "insert into students(id,name,age) values(%s,%s,%s)"
cursor.execute(sql,(id,name,age))
db.commit()
db.close()
通過三種sql語句的編寫形式我們能夠發(fā)現(xiàn)。方式3的最為簡潔,通過使用%s
來進(jìn)行占位,然后再通過execute()
函數(shù)將數(shù)據(jù)傳入sql語句中組成完整的sql語句。
在執(zhí)行execute()方法之后必須要commit()方法才能將數(shù)據(jù)插入到表中,這個設(shè)計到了事務(wù)的原子性問題,事務(wù)機(jī)制可以確保數(shù)據(jù)一致性,事務(wù)有4個屬性:原子性、一致性、隔離性、持久性。
屬性 | 描述 |
---|---|
原子性 | 事務(wù)是一個不可分割的工作單位,事務(wù)中包括的操作要么都執(zhí)行,要么都不執(zhí)行 |
一致性 | 事務(wù)必須是數(shù)據(jù)庫中一個一致性狀態(tài)轉(zhuǎn)變到另一個一致性狀態(tài),一致性與原子性是密切相關(guān)的 |
隔離性 | 一個事務(wù)不能被其他事務(wù)干擾,即一個事務(wù)內(nèi)部的操作及使用的數(shù)據(jù)對并發(fā)的其他事務(wù)時隔離的,并發(fā)的各個事務(wù)之間不能相互干擾 |
持久性 | 持久性也稱永久性,指一個事務(wù)一旦提交,它對數(shù)據(jù)庫中數(shù)據(jù)的改變就應(yīng)該是永久性的,接下來的其他操作或故障不應(yīng)該對其有任何影響 |
查詢數(shù)據(jù)
在數(shù)據(jù)庫操作的過程中使用最多的就是查詢操作
import pymysql
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
try:
sql = 'select * from students'
cursor = db.cursor()
cursor.execute(sql)
d1 = cursor.fetchone()
print("獲取一條數(shù)據(jù)",d1)
all_d = cursor.fetchall()
print("獲取所有數(shù)據(jù)",all_d)
# sql = "insert into students(id,name,age) values('"+id+"','"+name+"','"+age+"')"
except:
print("Error")
db.close()
數(shù)據(jù)庫中的數(shù)據(jù)
輸出:
通過結(jié)果我們能夠看到etchone()
執(zhí)行正常,拿出了一條數(shù)據(jù),但是fetchall()
明明是查詢所有,但是結(jié)果只有除了第一條之外的數(shù)據(jù),關(guān)于這個現(xiàn)象我們可以從游標(biāo)的角度來解釋,一開始游標(biāo)在第一行執(zhí)行etchone()
之后游標(biāo)就跑到第二行,再執(zhí)行fetchall()
的時候就從第二行開始查詢直至末尾。
可以簡單的理解etchone()查詢游標(biāo)所在的一行數(shù)據(jù),fetchall()查詢當(dāng)前游標(biāo)至結(jié)束的所有行數(shù)據(jù)。
使用where進(jìn)行條件查詢
查詢id大于10003的數(shù)據(jù)
import pymysql
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
try:
sql = 'select * from students where id>10003'
cursor = db.cursor()
cursor.execute(sql)
all_d = cursor.fetchall()
print("獲取所有數(shù)據(jù)",all_d)
# sql = "insert into students(id,name,age) values('"+id+"','"+name+"','"+age+"')"
except:
print("Error")
db.close()
輸出:
更新數(shù)據(jù)
跟新數(shù)據(jù),有時候我們再會對數(shù)據(jù)庫中原來的數(shù)據(jù)進(jìn)行修改
import pymysql
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
try:
sql = 'update students set name=%s where id=%s'
cursor = db.cursor()
cursor.execute(sql,('李四','10004'))
db.commit()
except:
db.rollback()
db.close()
刪除數(shù)據(jù)
根據(jù)條件刪除數(shù)據(jù),刪除id小于10004的數(shù)據(jù)
import pymysql
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
try:
sql = 'delete from students where id<%s'
cursor = db.cursor()
cursor.execute(sql,('10004'))
db.commit()
except:
db.rollback()
db.close()
實戰(zhàn)應(yīng)用
在實際應(yīng)用時,一般數(shù)據(jù)都是字典或者對象這種數(shù)據(jù),所以需要我們在拼接SQL語句的時候更加的靈活。
插入數(shù)據(jù),若數(shù)據(jù)存在更新數(shù)據(jù)
import pymysql
data = {
'id':'10006',
'name':'王五',
'age':45
}
# 連接數(shù)據(jù)庫
db = pymysql.connect(user='root',password='123456',host='localhost',port=3306,db='spiders')
table = 'students' # 表名
keys = ','.join(data.keys()) # 拼接插入的字段
values = ','.join(['%s']*len(data)) # 添加占位符
# 使用with關(guān)鍵字,Python 解釋器會自動釋放資源。 它還提供錯誤處理
with db:
cursor = db.cursor()
sql = 'insert into {}({}) values({}) on duplicate key update'.format(table, keys, values)
update = ','.join([" {key}=%s".format(key=key) for key in data])
sql += update
try:
cursor.execute(sql, tuple(data.values()) * 2)
db.commit()
except:
db.rollback()
可以發(fā)現(xiàn)在sql語句中有 on duplicate key update
:當(dāng)主鍵存在的時候更新數(shù)據(jù)。
我們可以根據(jù)cursor.execute()的返回值來判斷數(shù)據(jù)是插入操作還是更新操作文章來源:http://www.zghlxwxcb.cn/news/detail-779194.html
- 0 主鍵存在,且數(shù)據(jù)一樣沒有更新
- 1 主鍵不存在,插入數(shù)據(jù)
- 2 主鍵存在,更新操作
總結(jié)
通過pymysql我們實現(xiàn)了創(chuàng)建數(shù)據(jù)庫,創(chuàng)建表,以及對數(shù)據(jù)的增刪改查,這種基本的操作,通過這些我們也能夠發(fā)現(xiàn)pymysql的主要作用就是連接數(shù)據(jù)庫將指令傳遞給mysql,具體的功能實現(xiàn)還是需要我們自己編寫sql語句,因此在使用pymysql的前提是能夠熟練編寫sql語句。
關(guān)于pymysql的一些技巧以及優(yōu)化后面會有新的文章來講解文章來源地址http://www.zghlxwxcb.cn/news/detail-779194.html
到了這里,關(guān)于Python數(shù)據(jù)庫操作 ---- pymysql教學(xué)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!