Python如何操作MySQL?

前言

前面介紹了很多MySQL資料庫的知識,包括對資料的增刪改查,如何使用python操作MySQL就是本文的主題了,知道了如何使用python操作MySQL在後續開發中就無需使用檔案儲存程式中產生的資料了,激不雞凍

開不開森

pymysql模組簡介

pymysql是python的第三方模組,該模組提供了使用python連線mysql的方法,這樣我們可以透過程式碼連線並操作資料庫。

pymysql模組的安裝也非常簡單,在cmd命令列中輸入:

# 不指定版本預設安裝最新版本pip install pymysql複製程式碼

pymysql模組的基本使用

pymysql是第三方模組,使用時需要匯入,具體使用pymysql對資料進行增刪改查的操作請看下述程式碼:

import pymysql# 連線資料庫conn = pymysql。connect( user=‘root’, # 登入MySQL時的使用者名稱 password=‘1026’, # 密碼 host=‘127。0。0。1’, # MySQL的ip地址,本地就是127。0。0。1 port=3306, # MySQL的埠,沒有修改過的話就是3306 database=‘book_manage’, # 需要操作的資料庫的庫名 charset=‘utf8mb4’, # 資料庫的字符集 autocommit=True # 資料修改之後是否自動提交,True表示自動提交)# 獲取遊標物件,該物件用來執行SQL語句cursor = conn。cursor(pymysql。cursors。DictCursor)# 增——第一種方式executesql = ‘insert into author(name, age) values (“python”, 10), (“java”, 5);’rows = cursor。execute(sql) # rows是影響資料庫的行數# 增——第二種方式execute+字串格式化sql = ‘insert into author(name, age) values (%s, %s);’rows = cursor。execute(sql, (‘go’, 5))# 增——第三種方式增加多條,executemanysql = ‘insert into author(name, age) values (%s, %s);’rows = cursor。executemany(sql, [(‘php’, 10), (‘ruby’, 15), (‘js’, 20)])# 如果在建立連線時沒有指定autocommit=True,這裡就需要手動提交conn。commit() # 修改資料sql = ‘update author set name = %s where id = %s;’# 改一條rows = cursor。execute(sql, (‘haha’, 2))# 改多條rows = cursor。executemany(sql, [(‘haha’, 5), (‘xxx’, 3)])# 刪除資料sql = ‘delete from author where name = %s and id = %s;’# 執行一條刪除SQLrows = cursor。execute(sql, (‘xxx’, 3))# 執行多條刪除SQLrows = cursor。executemany(sql, [(‘haha’, 2), (‘haha’, 5)])# 查詢資料sql = ‘select * from author;’rows = cursor。execute(sql)# fetchall獲取查詢的所有結果result = cursor。fetchall()print(result)# fetchone獲取查詢結果中的第一條result1 = cursor。fetchone()print(result1)# fetchmany獲取查詢結果中的前n條,括號中寫幾就獲取前幾條資料result2 = cursor。fetchmany(3)複製程式碼

基於pymysql模組實現登陸和註冊

之前如果想要完成使用者的登入和註冊功能只能透過檔案的方式,有了MySQL之後可以將資料存放在資料庫中,無需使用檔案儲存,下面是基於pymysql模組操作資料庫實現的登入和註冊功能。

import pymysqlclass MyDBHandle: def __init__(self): self。conn = pymysql。connect( host=‘127。0。0。1’, port=3306, user=‘root’, passwd=‘123456’, db=‘userinfo’, charset=‘utf8’, autocommit=True ) self。cursor = self。conn。cursor(pymysql。cursors。DictCursor) def _db_handle_select(self, *args): sql = ‘select * from user where username=%s’ res = self。cursor。execute(sql, args) if not res: return {} else: return self。cursor。fetchone() def _db_handle_insert(self, *args): sql = ‘insert into user(username, password) values(%s, %s)’ self。cursor。execute(sql, args) def login_interface(self, name, pwd): user_dict = self。_db_handle_select(name) if not user_dict: return False, ‘使用者名稱不存在’ else: if pwd != user_dict。get(‘password’): return False, ‘使用者名稱或密碼錯誤’ return True, ‘登入成功’ def register_interface(self, name, pwd): user_dict = self。_db_handle_select(name) if user_dict: return False, ‘使用者名稱已經存在’ self。_db_handle_insert(name, pwd) return True, ‘註冊成功’class MyTest: def __init__(self, db_handle_obj): self。db_handle = db_handle_obj def run(self): while 1: cmd_list = [(‘登入’, ‘login’), (‘註冊’, ‘register’)] for index, item in enumerate(cmd_list): print(index, item[0]) cmd = input(‘請輸入功能編號:’)。strip() if not cmd。isdigit() or int(cmd) not in range(len(cmd_list)): continue cmd_func = cmd_list[int(cmd)][1] if hasattr(self, cmd_func): func = getattr(self, cmd_func) func() def login(self): while 1: username = input(‘username>>:’)。strip() password = input(‘password>>:’)。strip() flag, msg = self。db_handle。login_interface(username, password) print(msg) if flag: break def register(self): while 1: username = input(‘username>>:’)。strip() password = input(‘password>>:’)。strip() re_pwd = input(‘re_pwd>>:’)。strip() if re_pwd != password: print(‘兩次密碼輸入不一致’) continue flag, msg = self。db_handle。register_interface(username, password) print(msg) if flag: breakif __name__ == ‘__main__’: test = MyTest(MyDBHandle()) test。run()複製程式碼

結語

文章首發於微信公眾號程式媛小莊,同步於掘金、知乎。

作者:程式媛小莊

連結:https://juejin。cn/post/6977527735166238734