PyMySQL 安裝
在使用 PyMySQL 之前,我們需要確保 PyMySQL 已安裝。
PyMySQL 下載地址:https://github.com/PyMySQL/PyMySQL。
如果還未安裝,我們可以使用以下命令安裝最新版的 PyMySQL:
$ pip3 install PyMySQL
數據庫連接
通過如下代碼測試數據庫連接
1 #!/usr/bin/python3 2 3 import pymysql 4 5 # 打開數據庫連接 6 db = pymysql.connect("localhost","root","123456","mydb" ) 7 8 # 使用 cursor() 方法創建一個游標對象 cursor 9 cursor = db.cursor() 10 11 # 使用 execute() 方法執行 SQL 查詢 12 cursor.execute("SELECT VERSION()") 13 14 # 使用 fetchone() 方法獲取單條數據. 15 data = cursor.fetchone() 16 17 print ("Database version : %s " % data) 18 19 # 關閉數據庫連接 20 db.close()
下面通過實際操作來實現python操作mysql增刪改查
創建庫ops 添加字段信息 username,email,age,sex
創建服務器server.py
from http.server import HTTPServer, CGIHTTPRequestHandler port = 8080 httpd = HTTPServer((liang, port), CGIHTTPRequestHandler) print("Starting simple_httpd on port: " + str(httpd.server_port)) httpd.serve_forever()
通過本機ip訪問本機服務器
查看本機 ip linux下 命令行模式下輸入ifconfig
打開瀏覽器輸入服務器ip例如127.0.0.1:8080訪問
創建html文件index.html 和 add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <ul> <li><a href="/add.html">用戶添加</a></li> <li><a href="/cgi-bin/list.py">用戶列表</a></li> </ul> </body> </html> <!-- url http://127.0.0.1:8080/cgi-bin/list.py?a=123&b=345 http://www.baidu.com:80/cgi-bin/list.py 協議: http https ftp file ip 或 域名 端口: 8080 8090 (80 443) 路徑: /cgi-bin/list.py 請求方式: GET 參數 在url地址后面 以?分割 開始攜帶參數,多個參數之間用 & 分割 POST -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用戶添加</title> </head> <body> <form action="/cgi-bin/add.py" method="post"> 用戶名: <input type="text" name="username"><br> 郵箱: <input type="text" name="email"><br> 年齡: <input type="text" name="age"><br> 性別: <input type="radio" name="sex" value="0">女 <input type="radio" name="sex" value="1">男 <br> <button>添加</button> </form> </body> </html>
在當前目錄創建文件夾cgi-bin
進入文件夾
創建添加操作 add.py 注意如果無權限可以在當前文件夾打開終端 chmod 777 add.py 修改權限
#! /usr/bin/env python3 import cgi,pymysql print('Content-type:text/html;charset=utf-8') print() # 接受數據 fs = cgi.FieldStorage() # 根據key接收值 n = fs['username'].value data = {} for x in fs: # print(x) # print(fs[x].value) data[x] = fs[x].value # 打開數據庫連接 db = pymysql.connect("127.0.0.1","root","123456","py9",charset='utf8') # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # 准備sql語句 sql = 'insert into user(username,email,age,sex) values("{uname}","{uemail}",{uage},{usex})'.format(uname=data['username'],uemail=data['email'],uage=data['age'],usex=data['sex']) # print(sql) try: # 使用 execute() 方法執行 SQL cursor.execute(sql) # 提交執行 db.commit() print('<script>alert("添加成功");location.href="/cgi-bin/list.py";</script>') except: # 事務回滾 db.rollback() print('<script>alert("添加失敗");location.href="/add.html";</script>') # 關閉數據庫連接 db.close()
創建查看操作文件 list.py
#! /usr/bin/env python3 import cgi,pymysql print('Content-type:text/html;charset=utf-8') print() # 鏈接數據庫 # 打開數據庫連接 # db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8', cursorclass=pymysql.cursors.DictCursor) db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8') # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # 執行一個查詢的語句 sql = 'select * from stu' cursor.execute(sql) # 獲取結果 fetchone() 每次獲取一條數據 # res = cursor.fetchone() # fecthall() 獲取全部結果 res = cursor.fetchall() # print(res) trs = '' for x in res: s = '' if x[4] == 1: s = '男' else: s = '女' trs += ''' <tr> <td>{id}</td> <td>{name}</td> <td>{email}</td> <td>{age}</td> <td>{sex}</td> <td> <a href="/cgi-bin/delete.py?id={id}"">刪除</a> <a href="/cgi-bin/edit.py?id={id}">修改</a> </td> </tr> '''.format(id=x[0],name=x[1],email=x[2],age=x[3],sex=s) h = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用戶列表</title> </head> <body> <center> <table> <tr> <th>ID</th> <th>用戶名</th> <th>郵箱</th> <th>年齡</th> <th>性別</th> <th>操作</th> </tr> {} </table> </center> </body> </html> '''.format(trs) print(h) db.close() # 把數據放到html中顯示
創建修改 刪除 編輯 文件 edit.py
#! /usr/bin/env python3 import cgi,pymysql print('Content-type:text/html;charset=utf-8') print() # 接受數據 fs = cgi.FieldStorage() # 接收id uid = fs['id'].value # 打開數據庫連接 db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8') # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # 准備sql語句 sql = 'select * from stu where id = '+uid # 執行sql語句 cursor.execute(sql) # 獲取結果 uinfo = cursor.fetchone() sex = '' if uinfo[4] == 0: sex =''' 性別: <input type="radio" name="sex" value="0" checked>女 <input type="radio" name="sex" value="1">男 ''' else: sex =''' 性別: <input type="radio" name="sex" value="0" >女 <input type="radio" name="sex" value="1" checked>男 ''' html = ''' <form action="/cgi-bin/update.py" method="post"> <input type="hidden" name="id" value="{id}" /> 用戶名: <input type="text" name="username" value="{name}"><br> 郵箱: <input type="text" name="email" value="{email}"><br> 年齡: <input type="text" name="age" value="{age}"><br> {sex} <br> <button>修改</button> </form> '''.format(name=uinfo[1],email=uinfo[2],age=uinfo[3],sex=sex,id=uinfo[0]) print(html) # 關閉數據庫連接 db.close()
創建修改操作 文件 update.py
#! /usr/bin/env python3 import cgi,pymysql print('Content-type:text/html;charset=utf-8') print() # 接受數據 fs = cgi.FieldStorage() data = {} for x in fs: # print(x) # print(fs[x].value) data[x] = fs[x].value # print(data) # 打開數據庫連接 db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8') # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # 准備sql語句 sql = 'update stu set name="'+data['username']+'",email="'+data['email']+'",age='+data['age']+',sex='+data['sex']+' where id = '+data['id'] # print(sql) try: # 使用 execute() 方法執行 SQL cursor.execute(sql) # 提交執行 db.commit() print('<script>alert("修改成功");location.href="/cgi-bin/list.py";</script>') except: # 事務回滾 db.rollback() print('<script>alert("修改失敗");location.href="/cgi-bin/list.py";</script>') # 關閉數據庫連接 db.close()
創建刪除操作文件 delete.py
#! /usr/bin/env python3 import cgi,pymysql print('Content-type:text/html;charset=utf-8') print() # 接受數據 fs = cgi.FieldStorage() uid = fs['id'].value # print(uid) # 打開數據庫連接 db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8') # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # 准備sql語句 sql = 'delete from stu where id='+uid # print(sql) try: # 使用 execute() 方法執行 SQL cursor.execute(sql) # 提交執行 db.commit() print('<script>alert("刪除成功");location.href="/cgi-bin/list.py";</script>') except: # 事務回滾 db.rollback() print('<script>alert("刪除失敗");location.href="/cgi-bin/list.py";</script>') # 關閉數據庫連接 db.close()u
到這一步,python操作mysql增刪改查功能都實現了
溫馨提示
- 如果您對本文有疑問,請在評論部分留言,我會在最短時間回復。
- 如果本文幫助了您,也請評論關注,作為對我的一份鼓勵。
- 如果您感覺我寫的有問題,也請批評指正,我會盡量修改。
- 本文為原創,轉載請注明出處。
