Recipe 1.3 · Python
A Small Data Helper to Replace SqlHelper
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
The classic SqlHelper that many teams copied came from Microsoft's Data Access Application Block, released in 2002 for .NET Framework 1.0. It was useful at the time. It is now a liability: synchronous only, built around DataSet, overloads that take an open connection or a connection string or a transaction in every combination, and params object[] parameter lists that hide types. Teams keep it because removing it feels like a big job.
You do not need a large replacement. You need the three operations you actually use, with typed parameters and async.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
This shape is everywhere: about 9,585 files in the archive create a DataSet or DataTable, across 30 engagements. Everything is loaded into a DataSet, the values come back as object, and the static method encourages string-built SQL because parameters are awkward to pass.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""SqlHelper-style dataset call with concatenated SQL
Source: ImproveCode, Chapter 1, Recipe 1.3 "A Small Data Helper to Replace SqlHelper"
Section: The way it's often written
Book page: 23 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlHelper.ExecuteDataset -> a stand-in helper that opens pyodbc, fetchall()s into memory and
returns untyped rows (the DataSet/DataRow equivalent).
"""
import pyodbc
class SqlHelper:
@staticmethod
def execute_dataset(conn_string: str, sql: str) -> list[list[object]]:
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()
cursor.execute(sql)
return [list(r) for r in cursor.fetchall()]
def load_region_names(conn_string: str, code: str, names: list[str]) -> None:
# Not to copy: the typical SqlHelper-style call.
ds = SqlHelper.execute_dataset(
conn_string,
"SELECT Name FROM Region WHERE CountryCode = '" + code + "'")
for row in ds:
names.append(str(row[0]))
The improved recipe
Requirements: Python 3.12+. Install: pip install aioodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""A small async data helper to replace SqlHelper
Source: ImproveCode, Chapter 1, Recipe 1.3 "A Small Data Helper to Replace SqlHelper"
Section: The improved recipe
Book page: 23-24 -- original C# listing
Converted from C# to Python.
SqlClient -> aioodbc; Action<SqlParameterCollection> -> a callback that fills a TypedParams
(from the Recipe 1.2 file); CommandType.StoredProcedure -> ODBC "{CALL proc (?, ...)}" syntax;
CommandTimeout -> asyncio.timeout around execution; Func<SqlDataReader, T> -> Callable[[Row], T].
"""
import asyncio
from collections.abc import Callable
from enum import Enum
from typing import Any
import aioodbc
from p020_r1_2_typed_sql_parameters_lookup import DbConnectionFactory, TypedParams
ParamSetter = Callable[[TypedParams], Any]
class CommandType(Enum):
TEXT = "text"
STORED_PROCEDURE = "stored_procedure"
class Db:
def __init__(self, factory: DbConnectionFactory,
command_timeout_seconds: int = 30) -> None:
self._factory = factory
self.command_timeout_seconds = command_timeout_seconds
async def execute(self, sql: str, parameters: ParamSetter | None = None,
type: CommandType = CommandType.TEXT) -> int:
async with await self._factory.open() as connection:
async with connection.cursor() as command:
await self._run(command, sql, type, parameters)
return command.rowcount
async def scalar[T](self, sql: str, parameters: ParamSetter | None = None,
type: CommandType = CommandType.TEXT) -> T | None:
async with await self._factory.open() as connection:
async with connection.cursor() as command:
await self._run(command, sql, type, parameters)
row = await command.fetchone()
return None if row is None or row[0] is None else row[0]
async def query[T](self, sql: str, map: Callable[[Any], T],
parameters: ParamSetter | None = None,
type: CommandType = CommandType.TEXT) -> list[T]:
async with await self._factory.open() as connection:
async with connection.cursor() as command:
await self._run(command, sql, type, parameters)
results: list[T] = []
while (row := await command.fetchone()) is not None:
results.append(map(row))
return results
async def _run(self, command: aioodbc.Cursor, sql: str, type: CommandType,
parameters: ParamSetter | None) -> None:
if not sql or not sql.strip():
raise ValueError("sql must not be empty")
params = TypedParams()
if parameters is not None:
parameters(params)
if type is CommandType.STORED_PROCEDURE:
markers = ", ".join("?" for _ in params.values)
sql = f"{{CALL {sql} ({markers})}}" if markers else f"{{CALL {sql}}}"
if params.values:
await params.apply(command)
async with asyncio.timeout(self.command_timeout_seconds):
await command.execute(sql, *params.values)
How it works
Db wraps the connection factory from Recipe 1.1 and gives you three methods: execute a statement, read one value, read a list. Each opens a connection, runs one command and disposes everything before it returns. Parameters are added through a callback, which lets you use the typed extensions from Recipe 1.2 without any object[] in sight. Mapping is a function you pass in, so the helper never guesses at types.
The SqlHelper call above becomes:
That is the whole helper. I resist adding more to it. Every method you add is a method someone has to learn, and the things people usually want next (multiple result sets, output parameters, transactions) are clearer written directly against SqlCommand in the one place that needs them.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Using the Db helper for a query and a stored procedure
Source: ImproveCode, Chapter 1, Recipe 1.3 "A Small Data Helper to Replace SqlHelper"
Section: How it works
Book page: 24-25 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in an async function; lambdas fill TypedParams instead of SqlParameterCollection.
"""
from p023_r1_3_small_async_db_helper import CommandType, Db
async def usage(db: Db, code: str, customer_id: int) -> tuple[list[str], int]:
# Usage snippet
names: list[str] = await db.query(
"SELECT Name FROM dbo.Region WHERE CountryCode = ?;",
lambda r: str(r[0]),
lambda p: p.add_varchar("@Code", 2, code))
updated = await db.execute(
"dbo.Customer_Deactivate",
lambda p: p.add_int("@CustomerId", customer_id),
CommandType.STORED_PROCEDURE)
return names, updated
Variations and pitfalls
ScalarAsync<T>casts, it does not convert.(T)valueunboxes, so the C# type must match the SQL type exactly:intforINT,longforBIGINT,decimalforDECIMAL.COUNT(*)returnsINT;COUNT_BIG(*)returnsBIGINT. ForSCOPE_IDENTITY(), which returnsDECIMAL(38,0), read adecimalor cast in SQL.- Replacing SqlHelper gradually. You do not have to replace every call at once. Add
Dbalongside the old class, use it for new code, and convert old calls as you touch them. Search forSqlHelper.and the count should go down every sprint. - Why not a generic repository? A
Repository<T>that builds SQL from property names hides the SQL, which is the part you most need to see when tuning. If you want less hand mapping, use Dapper (next recipe) rather than writing your own ORM.
On .NET Framework
The class compiles on .NET Framework 4.7.2 and later if you replace the primary constructor with a normal constructor, use using blocks instead of await using on C# 7.3, and replace ArgumentException.ThrowIfNullOrWhiteSpace with an explicit check. The async methods on SqlCommand exist on 4.5 and later.