是否可以停止sqlite将双引号标识符视为字符串?

2024-05-15 05:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

根据:http://www.sqlite.org/draft/lang_keywords.html

如果您执行以下操作,SQLite3将执行您期望的操作:

select "foo" from bar;

但是,如果标识符不存在:

select "non-existant" from bar;

它退回(为了与旧版本兼容,我猜)将引用的文本视为字符串。你知道吗

这给我带来了问题,因为我使用这样的带引号的列动态地创建查询,而后面的行为返回的是无意义的结果,而不是抛出错误。你知道吗

我正在编写python代码,并使用一个封装了PEP-249python数据库API规范v2.0模块的模块,这样我就可以在必要时使用特定于数据库的hack。你知道吗

我们的后端数据库可能会改变(事实上,对于本地测试和生产,在某些时候可能会有所不同),所以如果可能的话,我希望保持SQL本身的标准。你知道吗

我有没有办法:

  • 停止/关闭此行为
  • 轻松/可靠地检测到发生了这种情况(并提出我自己的异常,例如)
  • 以某种方式解决这个问题(我不认为用非标准的等价物替换sql中的“in”很容易以安全的方式编程实现)

Tags: 模块fromorg数据库httplangsqlitehtml
2条回答

不要使用引号,使用[]

sqlite> create table blah (name text);
sqlite> select "something" from blah;
sqlite> select "name" from blah;
sqlite> insert into blah values ('hello');
sqlite> select "something" from blah;
something
sqlite> select "name" from blah;
hello
sqlite> select [something] from blah;
Error: no such column: something
sqlite> select [name] from blah;
hello
sqlite> 

尝试以编程方式混淆:

import re
from itertools import cycle

s = 'select "something" from blah;'
sel, cols, rest = re.match(r'(select)\s+(.*?)\s+(from\s+.*)', s).groups()
cols = re.sub('"', lambda g, I=cycle('[]'): next(I), cols)
print ' '.join( (sel, cols, rest) )
# select [something] from blah;

如果列名以表名或别名作为前缀,则不能误解它们:

SELECT bar."foo", a."baz" FROM bar, blah AS a

当您处理多个表时,可能无论如何都需要使用它来避免列名冲突。你知道吗

相关问题 更多 >

    热门问题