經過PyMySQL鏈接MySQL

安裝PyMySQLpython

  • 點擊開始按鈕--運行--輸入‘cmd’--輸入命令‘pip install PyMySQL’自動下載安裝
  • 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')

數據庫查詢操做數據庫

  • 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('讀取完畢')

例:建立註冊頁面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('新增失敗...')
相關文章
相關標籤/搜索