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.6.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 58b7ddcce08482505ad866959ecbfb7cd1b46da3d34eaed7777f887f624b0ffd |
|
MD5 | da8776038d0734822d4ef716bb112b70 |
|
BLAKE2b-256 | a7f144f3d42d9049473e9392b65cd69493ecdef910730e1bff18c7690bd88799 |
Close
Hashes for mysql_statement_builder-0.2.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 64020733236c9df379dad031506496440c046ec3be11ba6a5230497ecc014d66 |
|
MD5 | 593b5754694956fec04174157aa1b1a7 |
|
BLAKE2b-256 | 800edac059d4a336263e9c166c267c2f52b9d2b551e7e9b6ac9451ccd1c51873 |