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
Close
Hashes for mysql-statement-builder-0.2.3.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | b279ebda3cbb3c5a75081d7b35974332394b7c0bd76e1d9849e221fb87cccc98 |
|
MD5 | 31dc20aa857516ea007950893ee7f71b |
|
BLAKE2b-256 | d65be5e0c1dbbd4c441b540cb81523ba3db17e622a3c9d13f792ab49b5f8a1f3 |
Close
Hashes for mysql_statement_builder-0.2.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | beca6f2fa01194eb18ced7c1ab4c98cbfde670f9e735448a9c5d03bab8f894b4 |
|
MD5 | a198301cb8ade96a041e78943b3925eb |
|
BLAKE2b-256 | 7f4ac8ada3554e192ecef03c2671d2985db7b066b2196f0762c2f9c5da234174 |