sql >> Databasteknik >  >> RDS >> Mysql

Python Anslut till MySQL-databas med MySQL Connector &PyMySQL-exempel

När du vill ansluta till MySQL-databasen i Python-kod kan du använda både mysql-connector-python MySQL-drivrutin och PyMySQL . Den mysql-connector-python MySQL-drivrutinen är en MySQL-server inbyggd drivrutin och PyMySQL är ett tredjepartsbibliotek.

Alla de två MySQL pythonbiblioteken tillhandahåller klasser för dig att få MySQL-databasanslutning, exekvera infoga, ta bort, uppdatera, välj SQL-kommando. De stöder också transaktionshantering. Den här artikeln visar ett exempel på hur du använder mysql-connector-python och PyMySQL att arbeta på MySQL-databastabellen.

1. Hur man använder mysql-connector-python för att driva MySQL-databasen.

1.1 Installera mysql-connector-python Library.

  1. mysql-connector-python biblioteket kan installeras när du installerar MySQL-databasen.
  2. Så du kan köra kommandot pip show mysql-connector-python för att kontrollera om den har installerats eller inte.
    $ pip show mysql-connector-python
    WARNING: Package(s) not found: mysql-connector-python
  3. Om mysql-connector-python biblioteket inte är installerat kan du köra kommandot pip install mysql-connector-python för att installera 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ör kommandot pip show mysql-connector-python igen, du kan få dess installationsinformation.
    $ 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 Använd mysql-connector-python Anslut till MySQL-databas Steg.

  1. Importera mysql.connector class.
    import mysql.connector
  2. Anropa mysql.connector.connect() metod för att ansluta till MySQL databasserver.
    # 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 Kör DDL-satsen för att skapa en tabell.

  1. Hämta MySQL-databasmarkören.
    cursor = conn.cursor()
  2. Kör DDL-satsen. Om du vill köra flera DDL-satser samtidigt måste du separera varje DDL-sats med semikolon, och du bör lägga till multi=True
    parameter till markörobjektets execute() metod, annars kommer felet mysql.connector.errors.InterfaceError:Använd multi=True när du kör flera satser .

    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 Kör DML-utlåtande ( Infoga, Uppdatera, Ta bort ).

  1. Hämta MySQL-databasanslutningsmarkörobjekt.
  2. Kör insert, update, delete SQL-satsen med markörobjektets execute() metod.
    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. Om du vill infoga flera rader i MySQL-tabellen kan du köra markörobjektets executemany() metod.
    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 Kör DML Välj SQL-sats.

  1. Kör markörobjektets execute() metod för att köra vald SQL-sats.
    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. Hur man använder PtMySQL för att driva MySQL-databasen.

2.1 Installera PyMySQL.

  1. Innan du kan använda PyMySQL bör du installera det först. Du kan använda pip för att installera som nedan.
    $ pip3 install PyMySQL
  2. Du kan köra pip3 show kommando för att verifiera PyMySQL-installationen.
    $ pip3 show PyMySQL

2.2 Använd PyMySQL för att ansluta och driva MySQL-databasen.

Nedan är stegen som du använder PyMySQL-biblioteket i Python-kod.

  1. Importera PyMSQL connect , markörer class.
    from pymysql import connect, cursors
  2. Ring anslut metod för att hämta MySQL-databasanslutningsobjekt.
    conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
  3. Hämta databasmarkörobjekt genom anslutningsobjektets cursor()-funktion.
    conn.cursor() as cursor:
  4. Kör SQL-satsen med markörobjektet.
    cursor.execute(sql)
  5. Om sql-satsen är en select-sats, anropa markörobjektets fetchall()- eller fetchone()-metod för att få sql-exekveringsresultatet. Observera att efter att ha anropat fetchall(), kommer markören att flyttas till den sista raden i resultatet, så om du anropar fetchall()-metoden igen kommer ingen rad att returneras.
    row = cursor.fetchall()
    
    or
    
    row = cursor.fetchone()
  6. Om sql-satsen är en insert, update, delete-sats, anropa anslutningsobjektets commit()-funktion för att överföra ändringarna till MySQL-databasen för att träda i kraft.
    conn.commit()
  7. Glöm inte att stänga MySQL-databasanslutningsobjektet i slutet för att frigöra databasresurser.
    if conn is not None:
            conn.close()
            conn = None

2.3 PyMySQL Operate MySQL Database Exempel.

  1. I det här exemplet är MySQL-databasens namn dev2qa_example , tabellnamnet är användarkonto . Tabellen har fyra kolumner som är id , användarnamn , lösenord, och e-post . Id-kolumnen ökas automatiskt.
  2. Python-källkoden innehåller metoder för att infoga, uppdatera, ta bort och välja användarkontodata som nedan.
    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. Nedan är resultatet av kodexekveringen ovan.
    **********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.**********

Referenser

  1. Hur man använder MySql på Mac

  1. Hur REGEXP_INSTR() fungerar i MariaDB

  2. Jämför MariaDB Server med MariaDB Cluster

  3. SQL Server SP - Pass parameter för IN array lista?

  4. MySQL-motsvarighet till DECODE-funktionen i Oracle