作者:sergiojune
個人公眾號:日常學python
專注python爬蟲,數據可視化,數據分析,python前端技術
工欲善其事,必先利其器。所以第一步,我們先下載第三方庫。在這裡,我用到的是pymysql庫。
下載庫:在命令行輸入
下載後可檢驗一下是否成功下載。直接在命令行進入python然後導庫即可
1C:\Users\June>python
2Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
3Type "help", "copyright", "credits" or "license" for more information.
4>>> import pymysql
5>>>
看到這個畫面就說明下載成功了,接下來學習如何操作資料庫了!!!
連接資料庫
1import pymysql
2# 連接資料庫
3db = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',db='news',port=3306,charset='utf8')
以上的參數是必填的
host: 這個是ip地址,因為我這裡是本地的,所以填127.0.0.1,也可以填localhost。
user:用戶名,如果你也是本地的,就填root好了
passwd:這個是密碼,填上你自己設的密碼就可以了
db:這個是資料庫名,我這裡選的是news資料庫
port:這個是埠,本地的一般都是3306
charset:這個是編碼方式,要和你資料庫的編碼方式一致,要不會連接失敗
連接上了,怎麼驗證呢?這裡我們可以選擇查一條數據
1try:
2 db = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',db='news',port=3306,charset='utf8')
3 # 檢驗資料庫是否連接成功
4 cursor = db.cursor()
5 # 這個是執行sql語句,返回的是影響的條數
6 data = cursor.execute('SELECT * FROM `new`')
7 # 得到一條數據
8 one = cursor.fetchone()
9 print(data)
10 print(one)
11except pymysql.Error as e:
12 print(e)
13 print('操作資料庫失敗')
14finally:
15 # 如果連接成功就要關閉資料庫
16 if db:
17 db.close()
代碼解讀:因為在連接資料庫中,有時會發生連接失敗等異常,所以這裡就進行捕捉異常,這裡的異常都是在 pymsql.Error 裡面。上面的代碼看不懂也沒關係,因為我接下來會說,如果運行後有結果證明連接成功。
在用完後,一定要記得關閉資料庫連接,防止資源洩露問題。
對數據進行查詢
1import pymysql
2try:
3 conn = pymysql.connect(host='127.0.0.1',user='root',passwd='password',db='news',charset='utf8',port=3306)
4 # 這個是光標,用來操作資料庫語句
5 cursor = conn.cursor()
6 # 執行sql語句
7 cursor.execute('SELECT * FROM `new`')
8 print(cursor.fetchone())
9 # 關閉光標
10 cursor.close()
11except pymysql.Error as e:
12 print(e)
13 print('操作資料庫失敗')
14finally:
15 if conn:
16 conn.close()
代碼解讀:
cursor():這個是光標,用來執行mysql語句的,用完後也是需要關閉的
excute():這個是執行語句,執行參數的mysql語句
fetchone():這個是查看執行語句後的一條數據
fetchall():這個是查看所有數據
在查詢數據後,返回的是一整條數據,有沒有可以按字典形式來查詢的呢?來試試!
1print(cursor.fetchone()['name'])
2
3Traceback (most recent call last):
4 File "E:/anaconda/python_project/mysql_test/test2.py", line 8, in <module>
5 print(cursor.fetchone()['name'])
6TypeError: tuple indices must be integers or slices, not str
查了之後,編譯器想都不想就給了我這個錯誤,說這是個元組,不能這樣操作。
雖然python沒有提供,但是我們可以手動轉成字典來查詢啊
cursor這裡有個屬性:description。獲取的是資料庫每個欄位情況,如下:
1print(cursor.description)
2# 下面是結果
3(('id', 3, None, 11, 11, 0, False), ('type', 253, None, 5, 5, 0, False), ('title', 253, None, 50, 50, 0, False), ('content', 253, None, 2000, 2000, 0, False), ('view_count', 3, None, 11, 11, 0, False), ('release_time', 12, None, 19, 19, 0, False), ('author', 253, None, 20, 20, 0, True), ('from', 253, None, 20, 20, 0, True), ('is_valibale', 3, None, 11, 11, 0, False)
所以,我們利用這個屬性手動生成字典
1# 將一條數據轉成字典方便查找
2new = dict(zip([x[0] for x in cursor.description],[x for x in cursor.fetchone()]))
3print(new)
4# 下面是結果
5{'id': 2, 'type': 'NBA', 'title': '考辛斯跟腱撕裂賽季報銷 濃眉詹皇發聲祝福', 'content': '他遭遇左腳跟腱撕裂,將缺席賽季剩下的比賽。這無疑對考辛斯和鵜鶘隊都是一個重大的打擊', 'view_count': 3560, 'release_time': datetime.datetime(2018, 1, 27, 12, 10), 'author': 'xiaoylin', 'from': '騰訊體育', 'is_valibale': 1}
這裡利用zip函數和列表生成式來一行代碼就生成成功了
用字典來查詢,現在就可以了
1print(new['title'])
2# 下面是結果
3考辛斯跟腱撕裂賽季報銷 濃眉詹皇發聲祝福
但是,上面的只是一條數據的,如果是多條的呢?再按上面的方法就行不通了。這時就需要用到map函數了
1def new2dict(new):
2 return dict(zip([x[0] for x in cursor.description],[x for x in new]))
3news_list = list(map(new2dict,cursor.fetchall()))
4print(news_list)
5# 下面是結果
6[{'id': 2, 'type': 'NBA', 'title': '考辛斯跟腱撕裂賽季報銷 濃眉詹皇發聲祝福', 'content': '他遭遇左腳跟腱撕裂,將缺席賽季剩下的比賽。這無疑對考辛斯和鵜鶘隊都是一個重大的打擊', 'view_count': 3560, 'release_time': datetime.datetime(2018, 1, 27, 12, 10), 'author': 'xiaoylin', 'from': '騰訊體育', 'is_valibale': 1}, {'id': 3, 'type': 'NBA', 'title': '火箭挖21分大哈登得背鍋 連遭濃眉大帽太尷尬', 'content': '火箭在客場以113-115惜敗於鵜鶘,4連勝終結。詹姆斯-哈登出戰34分鐘16投5中,其中三分球9投只有1中,罰球14罰12中,拿到23分、11助攻、5籃板但也有4次失誤,其在場正負值為尷尬的-12分', 'view_count': 7520, 'release_time': datetime.datetime(2018, 1, 27, 12, 5), 'author': 'youngcao', 'from': '騰訊體育','is_valibale': 1}, {'id': 4, 'type': '英超', 'title': '足總杯-曼聯4-0英乙球隊晉級 桑神首秀造兩球', 'content': '2017-18賽季英格蘭足總杯第4輪,曼聯客場4比0擊敗英乙球隊約維爾,順利晉級下一輪。桑切斯迎來曼聯首秀,並製造了兩個入球', 'view_count': 6560, 'release_time': datetime.datetime(2018, 1, 27, 5, 49), 'author': 'ricazhang', 'from': '騰訊體育','is_valibale': 1}, {'id': 5, 'type': '英超', 'title': '這才配紅魔7號!桑神首秀大腿級表演 回擊噓聲質疑', 'content': '在今天凌晨對陣約維爾的首秀也值得期待。雖然在登場的72分鐘時間裡沒有進球,但送出1次助攻且有有6次威脅傳球的數據還是十分亮眼', 'view_count': 2760, 'release_time': datetime.datetime(2018, 1, 27, 6, 13), 'author': 'yaxinhao', 'from': '騰訊體育', 'is_valibale': 1}]
這裡很巧妙的利用了map函數,因為多條數據就可以進行迭代了,需要操作每條數據,這樣就可以想到map函數
接下來我們再用面向對象的方法來用python進行查詢資料庫
1import pymysql
2class MysqlSearch(object):
3 def get_conn(self):
4 '''連接mysql資料庫'''
5 try:
6 self.conn = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',port=3306,charset='utf8',db='news')
7 except pymysql.Error as e:
8 print(e)
9 print('連接資料庫失敗')
10
11 def close_conn(self):
12 '''關閉資料庫'''
13 try:
14 if self.conn:
15 self.conn.close()
16 except pymysql.Error as e:
17 print(e)
18 print('關閉資料庫失敗')
19
20 def get_one(self):
21 '''查詢一條數據'''
22 try:
23 # 這個是連接資料庫
24 self.get_conn()
25 # 查詢語句
26 sql = 'SELECT * FROM `new` WHERE `type`=%s'
27 # 這個光標用來執行sql語句
28 cursor = self.conn.cursor()
29 cursor.execute(sql,('英超',))
30 new = cursor.fetchone()
31 # 返回一個字典,讓用戶可以按數據類型來獲取數據
32 new_dict = dict(zip([x[0] for x in cursor.description],new))
33 # 關閉cursor
34 cursor.close()
35 self.close_conn()
36 return new_dict
37 except AttributeError as e:
38 print(e)
39 return None
40 def get_all(self):
41 '''獲取所有結果'''
42 sql = 'SELECT * FROM `new` '
43 self.get_conn()
44 try:
45 cursor = self.conn.cursor()
46 cursor.execute(sql)
47 news = cursor.fetchall()
48 # 將數據轉為字典,讓用戶根據鍵來查數據
49 news_list =list(map(lambda x:dict(zip([x[0] for x in cursor.description],[d for d in x])),news))
50 # 這樣也行,連續用兩個列表生成式
51 news_list = [dict(zip([x[0] for x in cursor.description],row)) for row in news]
52 cursor.close()
53 self.close_conn()
54 return news_list
55 except AttributeError as e:
56 print(e)
57 return None
58
59def main():
60 # 獲取一條數據
61 news = MysqlSearch()
62 new = news.get_one()
63 if new:
64 print(new)
65 else:
66 print('操作失敗')
67
68 # 獲取多條數據
69 news = MysqlSearch()
70 rest = news.get_all()
71 if rest:
72 print(rest)
73 print(rest[7]['type'],rest[7]['title'])
74 print('類型:{0},標題:{1}'.format(rest[12]['type'],rest[12]['title']))
75 for row in rest:
76 print(row)
77 else:
78 print('沒有獲取到數據')
79
80if __name__ == '__main__':
81 main()
這樣就可以通過實例的方法來進行查詢資料庫了
我們還可以根據頁數來進行查詢指定的數據數
1 def get_more(self,page,page_size):
2 '''查多少頁的多少條數據'''
3 offset = (page-1)*page_size
4 sql = 'SELECT * FROM `new` LIMIT %s,%s'
5 try:
6 self.get_conn()
7 cursor = self.conn.cursor()
8 cursor.execute(sql,(offset,page_size,))
9 news = [dict(zip([x[0] for x in cursor.description],new)) for new in cursor.fetchall()]
10 cursor.close()
11 self.close_conn()
12 return news
13 except AttributeError as e:
14 print(e)
15 return None
16
17def main():
18 #獲取某頁的數據
19 news = MysqlSearch()
20 new = news.get_more(3,5)
21 if new:
22 for row in new:
23 print(row)
24 else:
25 print('獲取數據失敗')
26
27if __name__ == '__main__':
28 main()
利用的是mysql的limit關鍵字,還有其他的,比如進行排序分組的感興趣的可以自己嘗試下
增加數據到資料庫
1 def add_one(self):
2 sql = 'INSERT INTO `new`(`title`,`content`,`type`,`view_count`,`release_time`) VALUE(%s,%s,%s,%s,%s)'
3 try:
4 self.get_conn()
5 cursor = self.conn.cursor()
6 cursor.execute(sql, ('title', 'content', 'type', '1111', '2018-02-01'))
7 cursor.execute(sql, ('標題', '內容', '類型', '0000', '2018-02-01'))
8 # 一定需要提交事務,要不不會顯示,只會佔位在資料庫
9 self.conn.commit()
10 return 1
11 except AttributeError as e:
12 print('Error:', e)
13 return 0
14 except TypeError as e:
15 print('Error:', e)
16 # 發生錯誤還提交就是把執行正確的語句提交上去
17 # self.conn.commit()
18 # 下面這個方法是發生異常就全部不能提交,但語句執行成功的就會佔位
19 self.conn.rollback()
20 return 0
21 finally:
22 cursor.close()
23 self.close_conn()
24
25 def main():
26 news = OperateSQL()
27 if news.add_one():
28 print('增加數據成功')
29 else:
30 print('發生異常,請檢查!!!')
31
32 if __name__ == '__main__':
33 main()
因為是增加數據,所以需要提交事務,這就需要用到conn .commit()來進行提交,在增加數據後,如果不提交,資料庫就不會顯示。
還有修改數據和刪除數據就不貼出來了,只是把上面的sql變量的語句改成修改或者刪除的語句就可以了,如果你還不會,建議練習下
END
代碼我放在github了,網站為https://github.com/SergioJune/gongzhonghao_code,有興趣的可以去看看,如果可以的話希望給個star哈!
這篇文章只適合入門的,如果需要學習更多的話可以去查看pymysql的文檔http://pymysql.readthedocs.io/en/latest/ 。
讚賞作者
Python愛好者社區歷史文章大合集:
Python愛好者社區歷史文章列表(每周append更新一次)
福利:文末掃碼立刻關注公眾號,「Python愛好者社區」,開始學習Python課程:
關注後在公眾號內回復「課程」即可獲取:
小編的Python入門視頻課程!!!
崔老師爬蟲實戰案例免費學習視頻。
丘老師數據科學入門指導免費學習視頻。
陳老師數據分析報告製作免費學習視頻。
玩轉大數據分析!Spark2.X+Python 精華實戰課程免費學習視頻。
丘老師Python網絡爬蟲實戰免費學習視頻。