Connect to MySQL via PyMySQL

Install PyMySQL

  • Click the start button -- run -- enter 'cmd' -- enter the command 'pip install PyMySQL' to automatically download and install
  • 	
    pip install PyMySQL

Python connects to MySQL, first import the pymysql package

  • import pymysql

Open MySQL connection host address (host) port number (port) database name (db) user name (user) password (password) character set encoding (chareset)

  • db=pymysql.connect(host='127.0.0.1',
                       port=3306,
                       db='python3',
                       user='root',
                       password='123456',
                       charset='utf8')

Database query operation

  • Python queries MYSQL to use the fetchone() method to obtain a single piece of data, and use the fetchall() method to obtain multiple pieces of data
  • fetchone(sql): This method gets the next query result set, the result set is an object
  • fetchall(): accepts all returned result rows
  • rowcount(): This is a read-only property and returns the number of rows affected after executing the execute() method

 

  • Enter the sql statement to query all the data in the database
  • sql='SELECT * FROM student'
  • Use the cursor() method to get the operation cursor
  • cur=db.cursor()
  • Send command and return result, stored in cursor
  • cur.execute(sql)
  • fetchall() accepts all returned result rows
  • rows=cur.fetchall()
    for r in rows:
        print('Student ID:{0}Telephone:{1}Name:{2}Gender:{3}'.format(r[0],r[1],r[2],r[3]))
    print('Reading finished')

Example: Create a registration page

  • #Import the pymysql package
    import pymysql
    
    #Open MySQL connection
    db=pymysql.connect(host='127.0.0.1',
                       port=3306,db='python3',
                       user='root',
                       password='123456',
                       charset='utf8')
    
    #User input input()
    studentNo=input('Please enter the student number:')
    
    #Check if the student number exists
    sql='''
        SELECT studentName FROM python3.student WHERE studentNo={0}
    '''.format(studentNo)
    
    #Use the cursor() method to get the operation cursor
    cursor=db.cursor()
    
    #Send the command and return the result, stored in the cursor
    cursor.execute(sql)
    
    #Get the next query result set, the result set is an object
    one_row=cursor.fetchone()
    
    # Determine if the student number exists
    if one_row is not None:
        print('Student ID already exists, please re-enter...')
    else:
        studentName=input('Please enter your name:')
        loginpwd= input('Please enter your password:')
        sex= input('Please enter gender:')
        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('Added successfully...')
        except:
            print('Add failed...')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325183748&siteId=291194637