TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Show HN: Easy placeholders for SQL queries when using psycopg2 in Python

1 点作者 rovyko大约 5 年前

1 comment

rovyko大约 5 年前
In <i>psycopg2</i>, variables can be inserted into queries using <i>%s</i> placeholders and supplying arguments to <i>cursor.execute</i>, but this does not allow for identifier arguments such as table or columns names. The alternative is to use <i>psycopg2.sql.SQL.format</i>, but this requires arguments to be converted into <i>Composable</i> objects such as <i>Literal</i> or <i>Identifier</i>.<p>With <i>TemplateQuery</i>, instead of wrapping arguments with <i>psycopg2.sql</i> classes (e.g. <i>Literal</i>, <i>Identifier</i>) the expected class can be written inside the query:<p><pre><code> &gt;&gt;&gt; TemplateQuery(&#x27;SELECT * FROM {table@Q} WHERE {@I} {@S} {value@L}&#x27;).format( ... &#x27;column_name&#x27;, &#x27;&gt;=&#x27;, table=&#x27;public.my_table&#x27;, value=100 ... ).as_string(conn) &#x27;SELECT * FROM &quot;public&quot;.&quot;my_table&quot; WHERE &quot;column_name&quot; &gt;= 100&#x27; </code></pre> The character after the at sign <i>@</i> in the placeholder key is the transformation that is applied to the argument before inserting it into the placeholder (<i>S</i> for raw SQL, <i>I</i> for Identifiers and <i>L</i> for literals, among others).<p>I wrote this small library while working on my master&#x27;s thesis to help run similar analysis queries on different tables and schema configurations, without the mental overhead of wrapping arguments in the proper classes. I&#x27;m not sure if it will be useful to anyone, but I thought it was worth releasing. Would appreciate any feedback at all!