Wrapper for the mysqlclient library using Python 3.
Create a virtual environment, install dependencies and load environment variables.
mkvirtualenv infmysql -p $(which python3)
dev/setup_venv.sh
source dev/env_develop
Run a MySQL Docker container.
dev/start_local_dependencies.sh
Note that project uses Alea's pydevlib, so take a look at its README to see the available commands.
Below is described the public API that this library provides.
The client can be initialized using the factory with a database URI and an optional parameter which determines if we want to use a dict cursor (false by default).
mysql_client = factory.mysql_client(database_uri, use_dict_cursor=False)
Executes a SQL query and returns the result. Passing parameters is possible by using %s
placeholders in the SQL query, and passing a sequence of values as the second argument of the function.
mysql_client.execute(query, params)
➡️ Parameters
- query:
str
- params (optional):
tuple<any>
. Defaults toNone
.
⬅️ Returns a tuple of tuples or dictionaries, each containing a row of results.
tuple<tuple<any>>
💥 Throws the same exceptions than the mysqlclient library.
from infmysql import factory
mysql_client = factory.mysql_client('mysql://username:password@host:port/databasename')
sql_query = 'SELECT (name, surname, age) FROM users WHERE age < %s AND active = %s;'
params = (30, True, )
result = mysql_client.execute(sql_query, params)
# (
# ('Ann', 'White', 18, ),
# ('Axel', 'Schwarz', 21, ),
# ('Camille', 'Rouge', '27', ),
# )
from infmysql import factory
mysql_client = factory.mysql_client('mysql://username:password@host:port/databasename', use_dict_cursor=True)
sql_query = 'SELECT (name, surname, age) FROM users WHERE age < %s AND active = %s;'
params = (30, True, )
result = mysql_client.execute(sql_query, params)
# (
# {'name': 'Ann', 'surname': 'White', 'age': 18},
# {'name': 'Axel', 'surname': 'Schwarz', 'age': 21},
# {'name': 'Camille', 'surname': 'Rouge', 'age': 27},
# )