Python + MySQL: verschil tussen versies
Naar navigatie springen
Naar zoeken springen
(18 tussenliggende versies door dezelfde gebruiker niet weergegeven) | |||
Regel 1: | Regel 1: | ||
== MySQL-driver == | == MySQL-driver == | ||
− | Om vanuit Python met MySQL te communiceren, heb je een ''driver'' nodig. | + | Om vanuit Python met MySQL te communiceren, heb je een ''driver'' nodig. Zie hiervoor artikel [[MySQL driver (Python)]]. |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
== ORM == | == ORM == | ||
− | De standaard-manier om te interacteren met een MySQL-database vanuit Python, is door SQL-commando's in strings te stoppen, en deze te executeren. Een verschrikkelijke manier: Complex, foutgevoelig en vermoedelijk lastig te debuggen. De oplossing voor dit probleem heet ''ORM'', oftewel ''object-relational mappings''. Hierdoor kun je rechtstreeks Python-db-gerelateerde commando's gebruiken | + | De standaard-manier om te interacteren met een MySQL-database vanuit Python, is door SQL-commando's in strings te stoppen, en deze te executeren. Een verschrikkelijke manier: Complex, foutgevoelig en vermoedelijk lastig te debuggen. De oplossing voor dit probleem heet ''ORM'', oftewel ''object-relational mappings''. Hierdoor kun je rechtstreeks Python-db-gerelateerde commando's gebruiken. |
=== Inventaris === | === Inventaris === | ||
Regel 41: | Regel 20: | ||
* SQLAlchemy - Lijkt de standaardoplossing te zijn. | * SQLAlchemy - Lijkt de standaardoplossing te zijn. | ||
− | === | + | == Programmeervoorbeelden == |
+ | |||
+ | === Mijn eerste db-connectie - Zonder ORM === | ||
+ | |||
+ | <pre> | ||
+ | #! /usr/bin/python | ||
+ | ##################################################################################### | ||
+ | # | ||
+ | import mysql.connector | ||
+ | |||
+ | cnx = mysql.connector.connect( | ||
+ | user='xxx', | ||
+ | password='yyy', | ||
+ | host='127.0.0.1', | ||
+ | database='zzz') | ||
+ | |||
+ | cursor = cnx.cursor() | ||
+ | |||
+ | cursor.execute("show databases;") | ||
+ | result=cursor.fetchall() | ||
+ | print result | ||
+ | |||
+ | cnx.close | ||
+ | </pre> | ||
− | + | Uitvoer - In een nogal gaar format (zie hieronder!): | |
− | |||
− | |||
− | |||
<pre> | <pre> | ||
− | + | [(u'information_schema',), (u'zzz',), (u'mysql',), (u'performance_schema',)] | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | ' | ||
</pre> | </pre> | ||
− | == | + | === Tuple unpacking === |
+ | |||
+ | Het gare format waarin data wordt weergegeven, is omdat ik samengestelde data (''tuples''?) als één object probeer weer te geven. De truuk is, om die data te splitsen [https://stackoverflow.com/questions/25121829/mysql-query-returns-data-uexample]: | ||
+ | |||
+ | <pre> | ||
+ | #! /usr/bin/python | ||
+ | # | ||
+ | # Bsp » Projecten - Actueel » P.'s importeren » XML-RPC » 06-py - Oct. 2018 | ||
+ | # Talk to MySQL-database & fetch data > Example http://www.mysqltutorial.org/python-mysql-query/ | ||
+ | ##################################################################################### | ||
+ | # | ||
+ | ##################################################################################### | ||
+ | # Load libraries | ||
+ | ##################################################################################### | ||
+ | # | ||
+ | import mysql.connector | ||
+ | |||
+ | # from mysql.connector import MySQLConnection, Error # Werkt niet + niet nodig | ||
+ | # from python_mysql_dbconfig import read_db_config # Werkt niet + niet nodig | ||
+ | |||
+ | |||
+ | def query_with_fetchall(): | ||
+ | try: | ||
+ | |||
+ | cnx = mysql.connector.connect( | ||
+ | user='xxx', | ||
+ | password='yyy', | ||
+ | host='127.0.0.1', | ||
+ | database='zzz') | ||
+ | |||
+ | |||
+ | cursor = cnx.cursor() | ||
+ | cursor.execute("SELECT * FROM practitioner_tmp") | ||
+ | rows = cursor.fetchall() | ||
+ | |||
+ | # Object "rows" contains all row data, as a tuple | ||
+ | ################################################# | ||
+ | # | ||
+ | print('Total Row(s):', cursor.rowcount) | ||
+ | i=0 | ||
+ | for row in rows: | ||
+ | |||
+ | i=i+1 | ||
+ | |||
+ | # Untuple | ||
+ | ################################################ | ||
+ | # | ||
+ | # https://stackoverflow.com/questions/25121829/mysql-query-returns-data-uexample | ||
+ | # | ||
+ | print(i), | ||
+ | print(row)[0], # Eerste veld | ||
+ | print(row)[1], # Etc. | ||
+ | print(row)[2], | ||
+ | print(row)[3] | ||
+ | |||
+ | except Error as e: | ||
+ | print(e) | ||
+ | |||
+ | finally: | ||
+ | cursor.close() | ||
+ | cnx.close() | ||
+ | |||
+ | |||
+ | if __name__ == '__main__': | ||
+ | query_with_fetchall() | ||
+ | </pre> | ||
− | == | + | == Zie ook == |
− | * | + | * [[MySQL-driver (Python)]] |
− | * | + | * [[SQLAlchemy]] |
+ | |||
+ | == Bronnen == | ||
=== ORM's === | === ORM's === | ||
Regel 76: | Regel 136: | ||
* https://pypi.org/project/SQLAlchemy/ | * https://pypi.org/project/SQLAlchemy/ | ||
* https://docs.sqlalchemy.org/en/latest/intro.html#installation - Installatie | * https://docs.sqlalchemy.org/en/latest/intro.html#installation - Installatie | ||
+ | |||
+ | === Fetch data (Connector/Python API) === | ||
+ | |||
+ | * https://www.google.com/search?q=python+mysql+read+data - Goed | ||
+ | * https://www.google.com/search?q=python+mysql+read+data+connector%2Fpython - Niet zo goed | ||
+ | * http://www.mysqltutorial.org/python-mysql-query/ |
Huidige versie van 19 jan 2019 om 23:00
MySQL-driver
Om vanuit Python met MySQL te communiceren, heb je een driver nodig. Zie hiervoor artikel MySQL driver (Python).
ORM
De standaard-manier om te interacteren met een MySQL-database vanuit Python, is door SQL-commando's in strings te stoppen, en deze te executeren. Een verschrikkelijke manier: Complex, foutgevoelig en vermoedelijk lastig te debuggen. De oplossing voor dit probleem heet ORM, oftewel object-relational mappings. Hierdoor kun je rechtstreeks Python-db-gerelateerde commando's gebruiken.
Inventaris
- SQLAchemy [1][2] - Vermoedelijk de meestgebruikte ORM
- peewee - Small & nimble
- Django-ORM
- Pony
- SQLObject
- Tortoise ORM
Keuze (okt. 2018)
- SQLAlchemy - Lijkt de standaardoplossing te zijn.
Programmeervoorbeelden
Mijn eerste db-connectie - Zonder ORM
#! /usr/bin/python ##################################################################################### # import mysql.connector cnx = mysql.connector.connect( user='xxx', password='yyy', host='127.0.0.1', database='zzz') cursor = cnx.cursor() cursor.execute("show databases;") result=cursor.fetchall() print result cnx.close
Uitvoer - In een nogal gaar format (zie hieronder!):
[(u'information_schema',), (u'zzz',), (u'mysql',), (u'performance_schema',)]
Tuple unpacking
Het gare format waarin data wordt weergegeven, is omdat ik samengestelde data (tuples?) als één object probeer weer te geven. De truuk is, om die data te splitsen [3]:
#! /usr/bin/python # # Bsp » Projecten - Actueel » P.'s importeren » XML-RPC » 06-py - Oct. 2018 # Talk to MySQL-database & fetch data > Example http://www.mysqltutorial.org/python-mysql-query/ ##################################################################################### # ##################################################################################### # Load libraries ##################################################################################### # import mysql.connector # from mysql.connector import MySQLConnection, Error # Werkt niet + niet nodig # from python_mysql_dbconfig import read_db_config # Werkt niet + niet nodig def query_with_fetchall(): try: cnx = mysql.connector.connect( user='xxx', password='yyy', host='127.0.0.1', database='zzz') cursor = cnx.cursor() cursor.execute("SELECT * FROM practitioner_tmp") rows = cursor.fetchall() # Object "rows" contains all row data, as a tuple ################################################# # print('Total Row(s):', cursor.rowcount) i=0 for row in rows: i=i+1 # Untuple ################################################ # # https://stackoverflow.com/questions/25121829/mysql-query-returns-data-uexample # print(i), print(row)[0], # Eerste veld print(row)[1], # Etc. print(row)[2], print(row)[3] except Error as e: print(e) finally: cursor.close() cnx.close() if __name__ == '__main__': query_with_fetchall()
Zie ook
Bronnen
ORM's
- https://en.wikipedia.org/wiki/Object-relational_mapping
- https://www.fullstackpython.com/object-relational-mappers-orms.html
- https://www.fullstackpython.com/django-orm.html
- https://www.fullstackpython.com/sqlalchemy.html
SQLAlchemy
- https://pypi.org/project/SQLAlchemy/
- https://docs.sqlalchemy.org/en/latest/intro.html#installation - Installatie