简体   繁体   English

Python sqlite3占位符

[英]Python sqlite3 placeholder

is there a way to set the placeholder for queries in sqlite3 ? 有没有办法在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和sqlite,它会更令人满意。 Mysql and Postgres python apis use the %s as a placeholder, but sqlite3 use a question mark instead. Mysql和Postgres python apis使用%s作为占位符,但sqlite3使用问号代替。

I'm looking for a way to use the same placeholder whatever the database engine. 我正在寻找一种方法来使用相同的占位符,无论数据库引擎如何。

Thanks for your help. 谢谢你的帮助。

Updated to fix my earlier error about how to use the paramstyle global 更新以修复我之前关于如何使用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: 如果您使用的数据库模块遵循Python数据库API规范v2.0 ,则可以获得模块全局参数paramstyle ,它应该是以下任何一种:

  1. 'qmark' Question mark style, eg '...WHERE name=?' 'qmark'问号样式,例如'... WHERE name =?'
  2. 'numeric' Numeric, positional style, eg '...WHERE name=:1' 'numeric'数字,位置样式,例如'... WHERE name =:1'
  3. 'named' Named style, eg '...WHERE name=:name' 'named'命名样式,例如'... WHERE name =:name'
  4. 'format' ANSI C printf format codes, eg '...WHERE name=%s' 'format'ANSI C printf格式代码,例如'... WHERE name =%s'
  5. 'pyformat' Python extended format codes, eg '...WHERE name=%(name)s' 'pyformat'Python扩展格式代码,例如'... WHERE name =%(name)s'

You can then compose your SQL statements with the placeholder used by the module. 然后,您可以使用模块使用的占位符来编写SQL语句。 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 }

The underlying library doesn't support %s , so it would need to be replaced manually. 底层库不支持%s ,因此需要手动替换它。 It might be easier to check the paramstyle attribute and replace all instances of a different placeholder in the query with an appropriate value instead. 检查paramstyle属性并使用适当的值替换查询中的其他占位符的所有实例可能更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM