通过PyMySQL连接MySQL
生活随笔
收集整理的這篇文章主要介紹了
通过PyMySQL连接MySQL
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
安裝PyMySQL
- 點擊開始按鈕--運行--輸入‘cmd’--輸入命令‘pip install PyMySQL’自動下載安裝
- pip install PyMySQL
Python連接MySQL,先導入pymysql包
- import pymysql
打開MySQL連接 主機地址(host) 端口號(port) 數據庫名字(db) 用戶名(user) 密碼(password) 字符集編碼(chareset)
- db=pymysql.connect(host='127.0.0.1',port=3306,db='python3',user='root',password='123456',charset='utf8')
數據庫查詢操作
- Python查詢MYSQL使用fetchone()方法獲取單條數據,使用fetchall()方法獲取多條數據
- fetchone(sql):該方法獲取下一個查詢結果集,結果集是一個對象
- fetchall():接受全部的返回結果行
- rowcount():這是一個只讀屬性,并返回執行execute()方法后影響的行數
?
- 輸入sql語句 查詢數據庫內所有
- sql='SELECT * FROM student'
- 使用cursor()方法獲取操作游標
- cur=db.cursor()
- 發送命令并返回結果,存儲在游標中
- cur.execute(sql)
- fetchall()接受全部的返回結果行
- rows=cur.fetchall() for r in rows:print('學號:{0}電話:{1}姓名:{2}性別:{3}'.format(r[0],r[1],r[2],r[3])) print('讀取完畢')
例:創建注冊頁面
- #導入pymysql包 import pymysql#打開MySQL連接 db=pymysql.connect(host='127.0.0.1',port=3306,db='python3',user='root',password='123456',charset='utf8')#用戶輸入 input() studentNo=input('請輸入學號:')#檢查學號是否存在 sql='''SELECT studentName FROM python3.student WHERE studentNo={0} '''.format(studentNo)#使用cursor()方法獲取操作游標 cursor=db.cursor()#發送命令并返回結果,存儲在游標中 cursor.execute(sql)#獲取下一個查詢結果集,結果集是一個對象 one_row=cursor.fetchone()#判斷學號是否存在 if one_row is not None:print('學號已存在,請重新輸入...') else:studentName=input('請輸入姓名:')loginpwd= input('請輸入密碼:')sex= input('請輸入性別:')insert_sql='''INSERT INTO python3.student(studentNo,loginPwd,studentName,sex)VALUES ('{0}','{1}','{2}','{3}');'''.format(studentNo,loginpwd,studentName,sex)try:cursor.execute(insert_sql)db.commit()print('新增成功...')except:print('新增失敗...')
轉載于:https://my.oschina.net/u/3764483/blog/1805783
總結
以上是生活随笔為你收集整理的通过PyMySQL连接MySQL的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 贷款都需要什么条件什么材料
- 下一篇: linux cmake编译源码,linu