在寫代碼的時候經(jīng)常遇到要操作數(shù)據(jù)庫,進(jìn)行增刪查改。目前比較流行的數(shù)據(jù)庫有很多,有關(guān)系型數(shù)據(jù)庫和非關(guān)系型數(shù)據(jù)庫,下面描述常見的MySQL、redis和MongoDB數(shù)據(jù)庫的python操作。
- 1.操作MySQL:
- python操作MySQL數(shù)據(jù)庫需要安裝第三方模塊進(jìn)行操作,python2中可以直接安裝MySQLdb模塊,可以直接通過
pip install MySQLdb進(jìn)行安裝使用。而在python3中沒有了MySQLdb模塊,可以用pymysql進(jìn)行替換,通過pip install pymysql安裝。下面介紹在python3中使用pymysql。
- python操作MySQL數(shù)據(jù)庫需要安裝第三方模塊進(jìn)行操作,python2中可以直接安裝MySQLdb模塊,可以直接通過
import pymysql
# 創(chuàng)建連接,指定數(shù)據(jù)庫的ip地址,端口號,賬號,密碼,數(shù)據(jù)庫,編碼格式
conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='root',db='database',charset='utf-8')
# 創(chuàng)建游標(biāo)
cursor=conn.cursor()
# 執(zhí)行SQL語句,并返回影響行數(shù)
effect_row=cursor.execute("update employees set name='employees1' where sid=0102")
effect_row=cursor.executemany("insert into employees (name,age)values(%s,%s);",[("zhangsan",20),("Lisi",21)])
# 執(zhí)行查詢語句
cursor.execute("select * from employees;")
# 獲取第一條數(shù)據(jù)
data=cursor.fechone()
# 獲取多少條數(shù)據(jù)
datas=cursor.fetchmany(100)
# 獲取所有的數(shù)據(jù)
data=cursor.fetchall()
# 提交所有操作修改
conn.commit()
cursor.close() # 關(guān)閉游標(biāo)
conn,close() #關(guān)閉連接
# 獲取自增id
lastId=cursor.lastrowid
- 2.一般情況之下,pymysql創(chuàng)建的cursor游標(biāo)都是返回一個操作結(jié)果的元組,如果想要操作的結(jié)果返回的是字典格式,可以指定創(chuàng)建的cursor游標(biāo)格式,其他的操作與上面相類似。
import pymysql
# 創(chuàng)建連接,指定數(shù)據(jù)庫的ip地址,端口號,賬號,密碼,數(shù)據(jù)庫,編碼格式
conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='root',db='database',charset='utf-8')
# 創(chuàng)建游標(biāo)
cursor=conn.cursor(cursor=pymsql.cursors.DictCursor)
-
- 操作Redis數(shù)據(jù)庫:
- redis是noSQL數(shù)據(jù)庫,基于計算機內(nèi)存,擁有很快的讀寫速度,之前做ip代理池時候,利用redis數(shù)據(jù)庫的隊列結(jié)構(gòu)很適合做入列與出列的操作。下面是python操作Redis數(shù)據(jù)庫的操作,python操作redis的主要模塊是redis
import redis
redis=redis.Redis(host="localhost",port="6379",db=1)
# 設(shè)置string類型的值
redis.set("name","value")
# 設(shè)置key為name的值,如果name不存在,才會進(jìn)行設(shè)置
redis.setnx("name","value")
# 設(shè)置key為name的值以及過期時間,過期之后,key值即將失效
redis.setex("name","value",3)
# 批量設(shè)置值
redis.mset(k1="v1",k2="v2")
# 獲取值
redis.get("name")
# 批量獲取值
redis.mget("name1","name2")
# 刪除值
redis.delete("name")
# 批量刪除值
redis.delete("name1","name2","name3")
# 操作哈希類型值
redis.hset("hname","name","value")
# 給name為hname設(shè)置name和value,當(dāng)name不存在時,才設(shè)置set
redis.hsetnx("hname","name","value")
# 批量設(shè)置哈希類型·
redis.hmset("hname",{"name1":"value1","name2":"value2"})
# 獲取哈希類型的值
redis,hget("hname","name")
# 獲取hname下的所有name和value
redis.hgetall("hname")
# 刪除哈希類型的name里面指定的值
redis.hdel("hname","name")
# 獲取所有的值
redis.keys()
- 3.Mongodb數(shù)據(jù)庫同樣是NoSQL數(shù)據(jù)庫,Mongodb是基于bson格式的數(shù)據(jù)庫,之前寫了很多的爬蟲案例都是直接使用mongodb數(shù)據(jù)庫進(jìn)行保存。所以現(xiàn)在記錄一下python操作mongdb數(shù)據(jù)的常用模塊pymongo。首先可以通過pip工具進(jìn)行下載pymongo。
# 連接mongodb數(shù)據(jù)庫
import pymongo
client=pymongo.MongoClient(host="127.0.0.1",port=27017)
# 也可以直接使用以下的方式進(jìn)行創(chuàng)建client
client=MongoClient("mongodb://localhost:27017")
# 指定要使用的數(shù)據(jù)庫
db=client["dbname"]
db=client.dbname
# 指定使用的集合,類似于mysql數(shù)據(jù)庫的表結(jié)構(gòu)
collection=db.collectionName
collection=db["collectionName"]
# 如果mongodb數(shù)據(jù)庫以授權(quán)驗證的形式啟動,還需要進(jìn)行數(shù)據(jù)庫驗證
db.authenticate(username,password)
# 數(shù)據(jù)形式
data={
"id":"1010101",
"name":"kiwis"
"age":20
}
# 插入數(shù)據(jù),插入數(shù)據(jù),會返回一個_id值,如果沒有設(shè)置這個字段值,則mongodb數(shù)據(jù)庫會自動生成一個object_id的值返回
collection.insert(data)
# 插入多條數(shù)據(jù),返回_id的集合
collection.insert([data1,data2])
# python3的官方pymongo推薦使用insert_one和insert_many方法插入一條或多條數(shù)據(jù)
#insert_one返回的值不再是_id值,而是InsertOneResult對象,可以通過對象獲取insert_id值(相當(dāng)于_id)
collection.insert_one(data)
# insert_many像上面一樣可以通過列表的形式進(jìn)行傳遞,insert_many方法返回的類型是InsertManyResult對象,通過其inserted_ids屬性可以獲取插入數(shù)據(jù)的_id列表
coilection.insert_many([data1,data2])
# 數(shù)據(jù)查詢,find_one與find分別可以查詢一條結(jié)果與多條結(jié)果數(shù)據(jù)
# find_one返回一條字典類型的數(shù)據(jù)
collection.find_one({"name":"kiwis"})
# find返回多條數(shù)據(jù),返回的結(jié)果是Cursor類型,相當(dāng)于一個generator生成器,如果需要迭代數(shù)據(jù),每一個結(jié)構(gòu)都是字典類型的數(shù)據(jù)
collection.find({})
# 例子迭代數(shù)據(jù)結(jié)果
datas=collection.find({})
for data in datas:
print(data["name"])
# 查詢的其他條件,下面是查詢name為kiwis,age大于20的數(shù)據(jù)結(jié)果
collection.find({"name":"kiwis","age":{"$gt":20}})
# 其他的篩選條件如下所示
# $ lt小于{"age":{"$lt":20}}
# $gt大于{"age":{"$gt":20}}
# $lte小于等于{"age":{"$lte":20}}
# $gte大于等于{"age":{"$gte":20}}
# $ne不等于{"age":{"$ne":20}}
# $in 在范圍之內(nèi){"age":{"$in":[10,30]}}
# $nin 不在范圍之內(nèi){"age":{"$nin"}}
# $regex 正則表達(dá)式篩選{"name":{"$regex":"kiwis$"}},表示已kiwis結(jié)尾的name值的數(shù)據(jù)
# $exists判斷屬性存在與否 {"name":{"$exists":True}}表示查詢name屬性存在值的數(shù)據(jù)
# $type屬性的類型值 {"name":{"$type":String}} name的類型為string
# $mod表示數(shù)字操作 {"age":{"$mod":[4,1]}}表示除4余1的數(shù)據(jù)項
# $text文本查詢{"$text":{"$search":"kiwis"}} text類型數(shù)據(jù)的屬性包含kiwis的字符串
# $where 條件查詢{"$where":"studentName==employeesName"}
# 對查詢到的數(shù)據(jù)進(jìn)行計數(shù)
collection.find({"age":{"$lt":20}}).count()
collection.find({}).count()
# 對查詢到的書籍進(jìn)行排序操作
collection.find({}).sort("name",pymongo.ASCENDING)
# 如果想跳過幾個數(shù)據(jù),進(jìn)行取值,可以直接使用skip
collection.find({}).skip(1)
# 獲取到的數(shù)據(jù)進(jìn)行數(shù)量的取值限制limit
collection.find({}).skip(1).limit(2)
collection.find({}).sort("age",pymongo.ASCENDING).skip(1).limit(2)
# 對數(shù)據(jù)進(jìn)行更新
collection.update({"name":"kiwis"},{"$set":{"age":23,"name":"laternkiwis"}})
collection.update({"name":"kiwis"},{"$set":{"age":23}})
# 如果有多個結(jié)果,是否全部修改
collection.update({"name":"kiwis"},{"$set":{"age":23}},multi=True)
# 刪除全部數(shù)據(jù)
collection.remove({})
# 刪除指定的數(shù)據(jù)
collection.remove({"name":"kiwis"})
上面總結(jié)都是常見的python操作數(shù)據(jù)方法,具體參照各個模塊的API說明文檔