sql >> Database teknologi >  >> RDS >> Mysql

Python Opret forbindelse til MySQL-database med MySQL Connector &PyMySQL-eksempel

Når du vil oprette forbindelse til MySQL-databasen i Python-kode, kan du bruge både mysql-connector-python MySQL-driver og PyMySQLmysql-connector-python MySQL-driveren er en MySQL-server indbygget driver og PyMySQL er et tredjepartsbibliotek.

Alle de to MySQL-pythonbiblioteker giver dig klasser, så du kan få MySQL-databaseforbindelse, udføre indsæt, slet, opdatere, vælg SQL-kommando. De understøtter også transaktionsstyring. Denne artikel viser dig et eksempel på, hvordan du bruger mysql-connector-python og PyMySQL at operere på MySQL-databasetabellen.

1. Sådan bruges mysql-connector-python til at betjene MySQL-databasen.

1.1 Installer mysql-connector-python-biblioteket.

  1. mysql-connector-python biblioteket kan installeres, når du installerer MySQL-databasen.
  2. Så du kan køre kommandoen pip show mysql-connector-python for at kontrollere, om det er blevet installeret eller ej.
    $ pip show mysql-connector-python
    WARNING: Package(s) not found: mysql-connector-python
  3. Hvis mysql-connector-python biblioteket ikke er installeret, kan du køre kommandoen pip install mysql-connector-python for at installere det.
    $ pip install mysql-connector-python
    Collecting mysql-connector-python
      Downloading mysql_connector_python-8.0.25-py2.py3-none-any.whl (319 kB)
         |████████████████████████████████| 319 kB 219 kB/s 
    Collecting protobuf>=3.0.0
      Downloading protobuf-3.17.0-cp37-cp37m-macosx_10_9_x86_64.whl (959 kB)
         |████████████████████████████████| 959 kB 727 kB/s 
    Requirement already satisfied: six>=1.9 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from protobuf>=3.0.0->mysql-connector-python) (1.15.0)
    Installing collected packages: protobuf, mysql-connector-python
    Successfully installed mysql-connector-python-8.0.25 protobuf-3.17.0
    
  4. Når du nu kører kommandoen pip show mysql-connector-python igen, du kan få dets installationsoplysninger.
    $ pip show mysql-connector-python
    Name: mysql-connector-python
    Version: 8.0.25
    Summary: MySQL driver written in Python
    Home-page: http://dev.mysql.com/doc/connector-python/en/index.html
    Author: Oracle and/or its affiliates
    Author-email: UNKNOWN
    License: GNU GPLv2 (with FOSS License Exception)
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: protobuf
    Required-by: 
    

1.2 Brug mysql-connector-python Opret forbindelse til MySQL-database.

  1. Importer mysql.connector klasse.
    import mysql.connector
  2. Bring mysql.connector.connect() metode til at oprette forbindelse til MySQL-databaseserver.
    # get mysql connection object.
    def open_mysql_connection(user='jerry', password='jerry', host='127.0.0.1', port='3306', database='dev2qa_example', use_unicode=True):
        conn = mysql.connector.connect(user=user, password=password, host=host, port=port, database=database, use_unicode=use_unicode)
        return conn

1.3 Udfør DDL-sætning for at oprette en tabel.

  1. Hent MySQL-databasemarkøren.
    cursor = conn.cursor()
  2. Kør DDL-sætning. Hvis du vil udføre flere DDL-sætninger på én gang, skal du adskille hver DDL-sætning med et semikolon, og du skal tilføje multi=True
    parameter til markørobjektets execute() metode, ellers vil den kaste fejlen mysql.connector.errors.InterfaceError:Brug multi=True, når du udfører flere sætninger .

    def execute_ddl(conn):
        cursor = conn.cursor()
        
        # The below DDL will first drop the table if exist, then create the table.
        ddl_sql= '''
        
           DROP TABLE user_account;
        
           CREATE TABLE `dev2qa_example`.`user_account` (
          `id` INT NOT NULL AUTO_INCREMENT,
          `user_name` VARCHAR(45) NULL,
          `password` VARCHAR(45) NULL,
          `email` VARCHAR(45) NULL,
          PRIMARY KEY (`id`));
           '''
        # Because the above DDL contains 2 statements ( drop, create), so need to add the multi=True parameter to avoid error mysql.connector.errors.InterfaceError: Use multi=True when executing multiple statements.
        cursor.execute(ddl_sql, multi=True)
        cursor.close()
        
        conn.close()
        
        print(ddl_sql + ' execute successfully.')

1.4 Udfør DML-erklæring (Indsæt, Opdater, Slet).

  1. Hent MySQL-databaseforbindelsesmarkørobjekt.
  2. Kør indsæt, opdater, slet SQL-sætning med markørobjektets execute() metode.
    def execute_dml(conn):
        
        cursor = conn.cursor()
        
        dml_insert = ''' INSERT INTO `dev2qa_example`.`user_account` VALUES (null, %s, %s, %s); ''' 
        
        cursor.execute(dml_insert, ('tom', 'tom12345678', '[email protected]'))
        
        conn.commit()
        
        cursor.close()
        
        conn.close()
    
  3. Hvis du vil indsætte flere rækker i MySQL-tabellen, kan du udføre markørobjektets executemany() metode.
    def execute_dml_insert_many(conn):
        
        cursor = conn.cursor()
        
        dml_insert = ''' INSERT INTO `dev2qa_example`.`user_account` VALUES (null, %s, %s, %s); ''' 
        
        row_tuple = (('richard', 'richard', '[email protected]'), ('trump', 'trump', '[email protected]'),('doctor', 'doctor', '[email protected]'))
        
        cursor.executemany(dml_insert, row_tuple)
        
        conn.commit()
        
        cursor.close()
        
        conn.close()

1.5 Udfør DML Vælg SQL-sætning.

  1. Kør markørobjektets execute() metode til at køre select SQL-sætning.
    def execute_dml_select(conn):
        
        cursor = conn.cursor()
        
        dml_select = 'SELECT * FROM dev2qa_example.user_account;'
        
        cursor.execute(dml_select)
        
        # print the row header.
        for col in cursor.description:
            
            print(col[0], end='\t')
            
            
        print('\n-----------------------------') 
        
        # print each row data.
        for row in cursor:
            
            print(row)   
            
            print(row[1] + '--->' + row[2])
               
            
        cursor.close()
        
        conn.close()

2. Sådan bruges PtMySQL til at betjene MySQL-databasen.

2.1 Installer PyMySQL.

  1. Før du kan bruge PyMySQL, bør du installere det først. Du kan bruge pip til at installere som nedenfor.
    $ pip3 install PyMySQL
  2. Du kan køre pip3 show kommando for at bekræfte PyMySQL-installationen.
    $ pip3 show PyMySQL

2.2 Brug PyMySQL til at oprette forbindelse og betjene MySQL-databasen.

Nedenfor er de trin, du bruger PyMySQL-biblioteket i Python-kode.

  1. Importer PyMSQL connect , markører klasse.
    from pymysql import connect, cursors
  2. Ring til Forbind metode til at hente MySQL-databaseforbindelsesobjekt.
    conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
  3. Hent databasemarkørobjekt ved forbindelsesobjektets cursor()-funktion.
    conn.cursor() as cursor:
  4. Kør SQL-sætningen med cursorobjektet.
    cursor.execute(sql)
  5. Hvis sql-sætningen er en select-sætning, skal du kalde cursorobjektets fetchall()- eller fetchone()-metode for at få sql-udførelsesresultatet. Bemærk venligst, efter at have påkaldt fetchall(), vil markøren flytte til den sidste række af resultatet, så hvis du kalder fetchall() metoden igen, vil der ikke få nogen række tilbage.
    row = cursor.fetchall()
    
    or
    
    row = cursor.fetchone()
  6. Hvis sql-sætningen er en insert, update, delete-sætning, så kald forbindelsesobjektets commit()-funktion for at overføre ændringerne til MySQL-databasen til at træde i kraft.
    conn.commit()
  7. Glem ikke at lukke MySQL-databaseforbindelsesobjektet i slutningen for at frigive databaseressourcer.
    if conn is not None:
            conn.close()
            conn = None

2.3 PyMySQL Betjen MySQL-databaseeksempel.

  1. I dette eksempel er MySQL-databasenavnet dev2qa_example , tabellens navn er brugerkonto . Tabellen har fire kolonner, der er id , brugernavn , adgangskode, og e-mail . Id-kolonnen øges automatisk.
  2. Python-kildekoden indeholder metoder til at indsætte, opdatere, slette og vælge brugerkontodata som nedenfor.
    from pymysql import connect, cursors
    
    global_host='127.0.0.1'
    global_user='jerry'
    global_password='jerry'
    global_db='dev2qa_example'
    global_charset='utf8'
    global_cursorclass=cursors.DictCursor
    
    # get mysql connection object.
    def open_mysql_connection(host='127.0.0.1', user='jerry', password='jerry', db='dev2qa_example', charset='utf8', cursorclass=cursors.DictCursor):
        conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
        return conn
        
    # close mysql connection.    
    def close_mysql_connection(conn):
        if conn is not None:
            conn.close()
            conn = None
    
    # execute insert, update or delete sql command.
    def execute_insert_update_delete_sql(sql, host, user, password, db, charset, cursorclass):
        execute_row_count = 0
        conn = None
        print('sql = ' + sql)
        try:
            if string_is_not_empty(sql):
                conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
                with conn.cursor() as cursor:
                    execute_row_count = cursor.execute(sql)
        except Exception as ex:
            print(ex)
        finally:
            if conn is not None:
                conn.commit()
                close_mysql_connection(conn)
            return execute_row_count    
     
    # execute select sql command.                    
    def execute_select_sql(sql, host, user, password, db, charset, cursorclass):
        ret = list()
        conn = None
        print('sql = ' + sql)
        try:
            if string_is_not_empty(sql):
                conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
                with conn.cursor() as cursor:
                    row_count = cursor.execute(sql)
                    print('select return row count = ' + str(row_count))
                    row = cursor.fetchall()
                    print(row)
                    ret.append(row)
        except Exception as ex:
            print(ex)            
        finally:
            if conn is not None:
                close_mysql_connection(conn)
            return ret        
    
    # insert user account to database table dev2qa_example.user_account.                
    def insert_user_account(user_name, password, email):
        print('**********Begin insert_user_account.**********')
        
        if string_is_not_empty(user_name) and string_is_not_empty(password) and string_is_not_empty(email):
            # first check whether user account exist or not.
            sql = "select count(id) as count from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
            row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
            
            account_exist = False
            for row in row_list:
                for column in row:
                    exist_count_number = column.get('count')
                    if exist_count_number > 0:
                        account_exist = True
            
            if not account_exist:
                print('User ' + user_name + ' do not exist in database. Insert the user account to database table.')
                sql = "insert into user_account(user_name, password, email) values('"+user_name+"','"+password+"','"+email+"')"
                insert_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
                print('Insert ' + str(insert_row_count) + ' row data successfully.')
            else:
                print('User account exist, can not insert.')    
        else:
            print('user_name, password, email can not be empty.')        
            
        print('**********End insert_user_account.**********')    
       
    # update user account data.            
    def update_user_account(user_name, password, email):
        print('**********Begin update_user_account.**********')
        
        if string_is_not_empty(user_name):
            sql = "update dev2qa_example.user_account set password = '" + password + "', email = '" + email + "' where lower(user_name) = '" + user_name.lower() + "'"
            update_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        
            if update_row_count == 0:
                print('User account do not exist, insert it now.')
                insert_user_account(user_name, password, email)
            else:
                print('Update ' + str(update_row_count) + ' row data successfully.')
        else:
            print('user_name can not be empty.')        
               
        print('**********End update_user_account.**********')
        
    # delete user account data from database table.    
    def delete_user_account(user_name):
        print('**********Begin delete_user_account.**********')
        
        if string_is_not_empty(user_name):
            sql = "delete from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower()+"'"
            delete_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
            print('Delete ' + str(delete_row_count) + ' row data successfully.')
            
        print('**********End delete_user_account.**********')
        
    # execute select sql command to get user account data by user_name.    
    def get_user_account_by_user_name(user_name):
        print('**********Begin get_user_account_by_user_name.**********')
        sql = "select * from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
        row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        print('**********End get_user_account_by_user_name.**********')
    
    # check whether the string is empty or not.
    def string_is_not_empty(str):
        if str is None:
            return False
        elif len(str.strip()) == 0:
            return False
        else:
            return True
    
    if __name__ == '__main__':
        # first delete user account jerry.
        delete_user_account('jerry')
        
        # then insert a user account jerry into database.
        insert_user_account('jerry', 'jerry', '[email protected]')
        # show user account data to verify the insert action.
        get_user_account_by_user_name('jerry')
        
        # update usr account information.
        update_user_account('jerry', 'jerry888', '[email protected]')
        # check the updated user account info again.
        get_user_account_by_user_name('jerry')
  3. Nedenfor er ovenstående kodeeksekveringsresultat.
    **********Begin delete_user_account.**********
    sql = delete from dev2qa_example.user_account where lower(user_name) = 'jerry'
    Delete 1 row data successfully.
    **********End delete_user_account.**********
    **********Begin insert_user_account.**********
    sql = select count(id) as count from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'count': 0}]
    User jerry do not exist in database. Insert the user account to database table.
    sql = insert into user_account(user_name, password, email) values('jerry','jerry','[email protected]')
    Insert 1 row data successfully.
    **********End insert_user_account.**********
    **********Begin get_user_account_by_user_name.**********
    sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'id': 42, 'user_name': 'jerry', 'password': 'jerry', 'email': '[email protected]'}]
    **********End get_user_account_by_user_name.**********
    **********Begin update_user_account.**********
    sql = update dev2qa_example.user_account set password = 'jerry888', email = '[email protected]' where lower(user_name) = 'jerry'
    Update 1 row data successfully.
    **********End update_user_account.**********
    **********Begin get_user_account_by_user_name.**********
    sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'id': 42, 'user_name': 'jerry', 'password': 'jerry888', 'email': '[email protected]'}]
    **********End get_user_account_by_user_name.**********

Referencer

  1. Sådan bruges MySql på Mac

  1. Sådan får du sidste 15 dages optegnelser i MySQL

  2. Lodret skalering af PostgreSQL

  3. Hvad er standardrækkefølgen for en liste, der returneres fra et Django-filteropkald?

  4. En oversigt over PostgreSQL 13 libpq sslpassword-forbindelsesparametre