问题描述
是否可以在sqlite3中设置查询的占位符?我有一些可以与数据库一起使用的功能,如果它们可以同时与mysql和sqlite一起使用,那就会更加令人满意.Mysql和Postgres python api使用%s作为占位符,而sqlite3使用问号代替.
is there a way to set the placeholder for queries in sqlite3 ?I have some functions that work with a database and it would be more satisfying if they could work both with mysql and sqlite.Mysql and Postgres python apis use the %s as a placeholder, but sqlite3 use a question mark instead.
我正在寻找一种使用相同占位符的方法,无论数据库引擎是什么.
I'm looking for a way to use the same placeholder whatever the database engine.
感谢您的帮助.
推荐答案
已更新,修复了我先前有关如何使用paramstyle
全局
Updated to fix my earlier error about how to use the paramstyle
global
如果您使用的数据库模块遵循 Python数据库API规范v2.0 ,您可以获取模块全局paramstyle
,该模块应为以下任意一个:
If the DB modules you use follow the Python Database API Specification v2.0, you can get the module global paramstyle
which should be any of these:
- "qmark"问号样式, 例如'... WHERE name =?'
- 数字"数字,位置样式, 例如'... WHERE name =:1'
- 命名"命名样式, 例如'... WHERE name =:name'
- 格式" ANSI C printf格式代码, 例如'... WHERE name =%s'
- "pyformat" Python扩展格式代码, 例如'... WHERE name =%(name)s'
- 'qmark' Question mark style, e.g. '...WHERE name=?'
- 'numeric' Numeric, positional style, e.g. '...WHERE name=:1'
- 'named' Named style, e.g. '...WHERE name=:name'
- 'format' ANSI C printf format codes, e.g. '...WHERE name=%s'
- 'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s'
然后,您可以使用模块使用的占位符来构成SQL语句.您可以执行以下操作:
You can then compose your SQL statements with the placeholder used by the module. You can do something like this:
import sqlite3
paramstyle = sqlite3.paramstyle
if paramstyle == 'qmark':
ph = "?"
elif paramstyle == 'format':
ph = "%s"
else:
raise Exception("Unexpected paramstyle: %s" % paramstyle)
sql = "INSERT INTO foo VALUES (%(ph)s, %(ph)s, %(ph)s)" % { "ph" : ph }
这篇关于Python sqlite3占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!