安裝PyMySQLpython
pip install PyMySQL
Python鏈接MySQL,先導入pymysql包mysql
import pymysql
打開MySQL鏈接 主機地址(host) 端口號(port) 數據庫名字(db) 用戶名(user) 密碼(password) 字符集編碼(chareset)sql
db=pymysql.connect(host='127.0.0.1', port=3306, db='python3', user='root', password='123456', charset='utf8')
數據庫查詢操做數據庫
sql='SELECT * FROM student'
cur=db.cursor()
cur.execute(sql)
rows=cur.fetchall() for r in rows: print('學號:{0}電話:{1}姓名:{2}性別:{3}'.format(r[0],r[1],r[2],r[3])) print('讀取完畢')
例:建立註冊頁面fetch
#導入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('新增失敗...')