教你用Python玩轉(zhuǎn)MySQL
大家好,我是辰哥。
爬蟲采集下來的數(shù)據(jù)除了存儲(chǔ)在文本文件、excel之外,還可以存儲(chǔ)在數(shù)據(jù)集,如:Mysql,redis,mongodb等,今天辰哥就來教大家如何使用Python連接Mysql,并結(jié)合爬蟲為大家講解。
前提:這里默認(rèn)大家已經(jīng)安裝好mysql。
01Mysql簡介
mysql是關(guān)系型數(shù)據(jù)庫,支持大型的數(shù)據(jù)庫,可以處理擁有上千萬條記錄的大型數(shù)據(jù)庫。通過爬蟲采集的數(shù)據(jù)集存儲(chǔ)到mysql后,可以借助mysql的關(guān)聯(lián)查詢將相關(guān)的數(shù)據(jù)一步取出。具體的作用這里就不贅述了,下面開始進(jìn)入實(shí)際操作。
1.安裝pymysql
通過下面這個(gè)命令進(jìn)行安裝
- pip install pymysql
pymysql庫:Python3鏈接mysql
備注:
ps:MYSQLdb只適用于python2.x
python3不支持MYSQLdb,取而代之的是pymysql
運(yùn)行會(huì)報(bào):ImportError:No module named 'MYSQLdb'
2.python連接mysql
- import pymysql as pmq
- #connect(ip.user,password,dbname)
- con = pmq.connect('localhost','root','123456','python_chenge')
- #操作游標(biāo)
- cur = con.cursor()
localhost是本機(jī)ip,這里用localhost表示是當(dāng)前本機(jī),否則將localhost改為對應(yīng)的數(shù)據(jù)庫ip。
root是數(shù)據(jù)庫用戶名,123456是數(shù)據(jù)庫密碼,python_chenge是數(shù)據(jù)庫名。
圖上的數(shù)據(jù)庫python_chenge已經(jīng)建立好(建好之后,才能用上面代碼去連接),建好之后,當(dāng)前是沒有表的,現(xiàn)在開始用Python進(jìn)行建表,插入、查詢,修改,刪除等操作(結(jié)合爬蟲去講解)
02建表
在存儲(chǔ)之前,先通過python創(chuàng)建表,字段有四個(gè)(一個(gè)主鍵+電影名稱,鏈接,評分)
- # 創(chuàng)建 movie 表
- movie_sql= '''
- create table movie(
- id int AUTO_INCREMENT primary key not null,
- title varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci not null,
- url varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci not null,
- rate float not null
- )
- '''
- # 執(zhí)行sql語句
- cur.execute(movie_sql)
- # 提交到數(shù)據(jù)庫執(zhí)行
- con.commit()
創(chuàng)建表movie,字段分別為(id ,title ,url ,rate ),CHARACTER SET utf8 COLLATE utf8_general_ci是字符串編碼設(shè)置為utf8格式
id是主鍵primary key,int類型,AUTO_INCREMENT自增,非空not null
title,url 是字符串類型varchar(100),同樣非空
評分rate 是帶小數(shù)的數(shù)字,所以是float,同樣非空
03插入數(shù)據(jù)
爬蟲已經(jīng)采集到數(shù)據(jù),python已經(jīng)建好表,接著可以將采集的數(shù)據(jù)插入到數(shù)據(jù)庫,這里介紹兩種方式
- ### 插入數(shù)據(jù)
- def insert(title,url,rate):
- # 插入數(shù)據(jù)一
- #cur.execute("INSERT INTO movie(title,url,rate) VALUES('"+str(title)+"','"+str(url)+"',"+str(rate)+")")
- # 插入數(shù)據(jù)二
- sql = "INSERT INTO movie(title,url,rate) VALUES('"+str(title)+"','"+str(url)+"',"+str(rate)+")"
- cur.execute(sql)
- # 提交到數(shù)據(jù)庫執(zhí)行
- con.commit()
id是自增的,所以不需要在傳值進(jìn)去。
定義好插入數(shù)據(jù)庫方法后,開始往數(shù)據(jù)庫進(jìn)行存儲(chǔ)
- for i in json_data['subjects']:
- insert(i['title'],i['url'],i['rate'])
04查詢
1.查詢所有
查詢表中所有數(shù)據(jù)
- # 查詢
- cur.execute('select * from movie')
- results = cur.fetchall()
- for row in results:
- Id = row[0]
- title = row[1]
- print("id=%s,title=%s" % (Id, title))
2.查詢指定的數(shù)據(jù)
比如查詢標(biāo)題為:唐人街3這一條數(shù)據(jù)的所有字段
- #查詢單條
- cur.execute('select * from movie where title="唐人街探案3"')
- results = cur.fetchall()
- for row in results:
- Id = row[0]
- title = row[1]
- url = row[2]
- rate = row[3]
- print("id=%s,title=%s,url=%s,rate=%s" % (Id, title,url,rate))
05更新修改
更新數(shù)據(jù),還是以上面:唐人街3為例,id為7,將唐人街3評分從5.5改為6
- ### 更新
- def update():
- sql = "update movie set rate='6' where Id = {0}".format(7)
- cur.execute(sql)
- con.commit()
同時(shí)看一下數(shù)據(jù)庫
06刪除
同樣還是以唐人街為例,其id為7,刪除的話咱們可以更新id去刪除
- def delete(Id):
- sql = "delete from movie where Id = {0}".format(Id)
- cur.execute(sql)
- con.commit()
刪除之后,就沒有第7條數(shù)據(jù)了,說明刪除成功
07小結(jié)
今天的技術(shù)講解文章就到此結(jié)束,主要是將了如何通過python去連接mysql,并進(jìn)行建表,插入數(shù)據(jù),查詢,更新修改和刪除。
本文轉(zhuǎn)載自微信公眾號「Python研究者」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Python研究者公眾號。