Wanneer u verbinding wilt maken met de MySQL-database in Python-code, kunt u zowel de mysql-connector-python gebruiken MySQL-stuurprogramma en PyMySQL . De mysql-connector-python MySQL-stuurprogramma is een MySQL-server ingebouwd stuurprogramma en de PyMySQL is een bibliotheek van derden.
Alle twee MySQL-pythonbibliotheken bieden klassen waarmee u een MySQL-databaseverbinding kunt krijgen, invoegen, verwijderen, bijwerken en SQL-opdracht kunt selecteren. Ze ondersteunen ook transactiebeheer. Dit artikel laat je een voorbeeld zien van het gebruik van mysql-connector-python en PyMySQL om te werken op de MySQL-databasetabel.
1. Hoe mysql-connector-python te gebruiken om MySQL-database te bedienen.
1.1 Installeer mysql-connector-python-bibliotheek.
- De mysql-connector-python bibliotheek kan worden geïnstalleerd wanneer u de MySQL-database installeert.
- Je kunt dus het commando
pip show mysql-connector-python
uitvoeren om te controleren of het is geïnstalleerd of niet.$ pip show mysql-connector-python WARNING: Package(s) not found: mysql-connector-python
- Als de mysql-connector-python bibliotheek niet is geïnstalleerd, kunt u het commando
pip install mysql-connector-python
uitvoeren om het te installeren.$ 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
- Als je nu het commando
pip show mysql-connector-python
uitvoert nogmaals, je kunt de installatie-informatie krijgen.$ 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 Gebruik mysql-connector-python Verbinding maken met MySQL-database Stappen.
- Importeer de mysql.connector class.
import mysql.connector
- Roep de mysql.connector.connect() . op methode om verbinding te maken met de 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 Voer een DDL-instructie uit om een tabel te maken.
- Haal de MySQL-databasecursor op.
cursor = conn.cursor()
- Voer DDL-instructie uit. Als u meerdere DDL-instructies tegelijk wilt uitvoeren, moet u elke DDL-instructie scheiden met een puntkomma en moet u de multi=True toevoegen
parameter voorexecute()
> van het cursorobject methode, anders geeft het de fout mysql.connector.errors.InterfaceError:Gebruik multi=True bij het uitvoeren van meerdere instructies .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 Voer DML-instructie (invoegen, bijwerken, verwijderen) uit.
- Verkrijg MySQL-databaseverbindingscursorobject.
- Voer de insert, update, delete SQL-instructie uit met
execute()
van het cursorobject methode.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()
- Als u meerdere rijen in de MySQL-tabel wilt invoegen, kunt u
executemany()
van het cursorobject uitvoeren methode.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 Voer DML Select SQL-instructie uit.
- Voer
execute()
van het cursorobject uit methode om select SQL-instructie uit te voeren.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. Hoe PtMySQL te gebruiken om MySQL-database te bedienen.
2.1 PyMySQL installeren.
- Voordat u PyMySQL kunt gebruiken, moet u het eerst installeren. Je kunt pip gebruiken om te installeren zoals hieronder.
$ pip3 install PyMySQL
- U kunt
pip3 show
uitvoeren commando om de PyMySQL-installatie te verifiëren.$ pip3 show PyMySQL
2.2 PyMySQL gebruiken om MySQL-database te verbinden en te bedienen.
Hieronder staan de stappen waarmee u de PyMySQL-bibliotheek in Python-code gebruikt.
- Importeer de PyMSQL connect , cursors class.
from pymysql import connect, cursors
- Bel verbinden methode om MySQL-databaseverbindingsobject te krijgen.
conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
- Verkrijg databasecursorobject door de cursor()-functie van het verbindingsobject.
conn.cursor() as cursor:
- Voer de SQL-instructie uit met het cursorobject.
cursor.execute(sql)
- Als de sql-instructie een select-instructie is, roept u de methode fetchall() of fetchone() van het cursorobject aan om het SQL-uitvoeringsresultaat te krijgen. Houd er rekening mee dat na het aanroepen van fetchall(), de cursor naar de laatste rij van het resultaat wordt verplaatst, dus als u de methode fetchall() opnieuw aanroept, wordt er geen rij geretourneerd.
row = cursor.fetchall() or row = cursor.fetchone()
- Als de sql-instructie een insert, update, delete-instructie is, roept u de functie commit() van het verbindingsobject aan om de wijzigingen in de MySQL-database door te voeren.
conn.commit()
- Vergeet niet om het MySQL-databaseverbindingsobject aan het einde te sluiten om databasebronnen vrij te geven.
if conn is not None: conn.close() conn = None
2.3 PyMySQL Gebruik MySQL-databasevoorbeeld.
- In dit voorbeeld is de naam van de MySQL-database dev2qa_example , de tabelnaam is user_account . De tabel heeft vier kolommen die id . zijn , gebruikersnaam , wachtwoord, en e-mail . De ID-kolom wordt automatisch verhoogd.
- De broncode van Python bevat methoden voor het invoegen, bijwerken, verwijderen en selecteren van gebruikersaccountgegevens zoals hieronder.
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')
- Hieronder staat het bovenstaande resultaat van de uitvoering van de code.
**********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.**********
Referenties
- Hoe MySql op Mac te gebruiken