Simplifies writing MySQL statements in non-ORM environments.
Project description
MySQL-statement-builder (mysqlsb)
...
Installation
pip install mysql-statement-builder
Usage
import mysql.connector
from mysql.connector import pooling
from contextlib import contextmanager
from mysqlsb import MySQLStatementBuilder, FetchType
# Setup a connection pool using the MySQL python connector
connection_pool = mysql.connector.pooling.MySQLConnectionPool(
user='user',
password='password',
host='host',
database='database',
port='port',
autocommit=False,
)
# Setup a method for recieving a connection from the connection pool
@contextmanager
def get_connection() -> pooling.PooledMySQLConnection:
"""
Returns a MySQL connection that can be used for read/write.
"""
connection = connection_pool.get_connection()
try:
yield connection
finally:
connection.close()
# Apply mysql-statement-builder to select data from the database
def get_user_from_database(user_id: int):
with get_connection() as connection:
mysql_statement = MySQLStatementBuilder(connection)
user_data = mysql_statement \
.select('users', ['id', 'username', 'email']) \
.where('id = %s', [user_id]) \
.execute(fetch_type=FetchType.FETCH_ONE, dictionary=True)
if user_data is None:
raise UserNotFoundException('User could not be found in database')
user = User(**user_data) # Unpack results dictionary into e.g. a Pydantic basemodel class
return user
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file mysql-statement-builder-0.3.0.tar.gz
.
File metadata
- Download URL: mysql-statement-builder-0.3.0.tar.gz
- Upload date:
- Size: 7.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6a445888167052df24e2c2f5092f088eb3459ea00503086c94745f28765a14e8 |
|
MD5 | 8b8978952659043f3323a77d73370cb3 |
|
BLAKE2b-256 | 83c317ca7cb8cb7844a644452d17a2d0a51abe76752184917e7aec174cd78915 |
File details
Details for the file mysql_statement_builder-0.3.0-py3-none-any.whl
.
File metadata
- Download URL: mysql_statement_builder-0.3.0-py3-none-any.whl
- Upload date:
- Size: 9.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6203f946a47d2b8de9d69d08d1f2381ba428e5e7b748119952928274e7c44126 |
|
MD5 | 8c9bd71ba2a3bd782226cde4c2e7e511 |
|
BLAKE2b-256 | b3372f8c9fe9d31221cb4def7a0de7d6377045085d257267a8adb0d8e5cc439e |