Use of locals() with SQL placeholders
"Peter J. Holzer" <[email protected]>
| Newsgroups | gmane.comp.python.general |
|---|---|
| Message-ID | <upvyatibrtuhm2ikp7kyxc4eelxdrxsc4zkurciisiarutbtbq@uqnozvw5mmh4> |
The Python database API allows the use of a dict to specify the values
for the placeholders in the SQL statement.
For example:
csr = conn.cursor()
...
csr.execute(
"""
select feature as name, description as label
from service s join permission p on s.id = p.service
where type = %(service_type)s
and p.login = %(login_id)s
and p.start_date <= %(horizon)s
and %(horizon)s < coalesce(p.end_date, 'infinity')
order by sort, description, feature
""",
{
"service_type": "login",
"login_id": 12345,
"horizon": datetime.datetime.now(),
}
)
Quite often the values already exist in local variables:
service_type = "login"
login_id = 12345
horizon = datetime.datetime.now()
Then the dict often becomes a bit repeitive:
csr.execute(
""" ... omitted for brevity ... """,
{
"service_type": service_type,
"login_id": login_id,
"horizon": horizon,
}
)
Therefore I have recently started to use locals() for the dict:
csr.execute(
""" ... omitted for brevity ... """,
locals()
)
Pros:
* it looks very clean
* it makes the code shorter
* The names of the placeholders are always in sync with the names of
local variables
Cons:
* Less explicit, so it may not be as obvious what the parameters are
* All local variables are exposed to execute, not just those it needs
What do you guys think?
hjp
--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | [email protected] | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
signature.asc
(application/pgp-signature, 833 B)
-----BEGIN PGP SIGNATURE----- iQIzBAABCgAdFiEETtJbRjyPwVTYGJ5k8g5IURL+KF0FAmqZQtkACgkQ8g5IURL+ KF3CMxAAkJ9DnR0sAG1FblpQbt+Guq7Fx8wTmxZ9aSZU/MGVEDE0XSHiElSeFenH Z/8hru8lKcmIFtTLtlHUFMNhZFjFSnkuQcIusCS3W71mDBFI7M6wtnxTUti1jKRN kXN/wEzxXRG43dJ1uVBXwGSibpOjsh+8ikOj/rQ5Pkm511rNJI+zxtw8Suy495YL 9lCcGfy093JRN7bmcyLCJRF0f/F9iQAgq2PZT0jcW6HmnWXjblFbNggygIRnQySK /up10vrd93+lZB3ANBT/DEpb2ecC2e7100EI8qw/8P1XBylaaMQw+9qgeERgur0X mw9L40+fRCDZxc2ML+cyv5h6FxWsYoG8l6mYXKlvpkvAjW2l+y+asWU4o/va0QMW /teCDrhLv3rIZBaN4mF4hjZu7mmSxFQvgBT8ODdqBtDjGCQjXd7SyR/5qQWmoF1x fJb73RrkPrKLPrTXl9mTTLH/Y8CYwj+JVM7zhQ0ZuzRhhjN12HPSUsvFXF47KcBU zJItCFcnq5OpMcyghCoL9Z0xNhkWYV0nDz/diS1AyGtoERvWZsqeEsqxRXJRVNcK euxtxOjtZJKlV5V2vNH44H/tYqMZp15JRik685++NV3iA4H80B20HmGOLNK1xzbo QuULsgx8Gpp5Ku8t1KzngsAIlyq4wX8f9J8CuWH/+SB60f2dAHI= =bnPs -----END PGP SIGNATURE-----