sqlite3多变量python查询

2024-03-29 12:07:25 发布

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

我到处寻找我问题的答案,但没有找到好的答案。。。。我使用python和sqlite3模块来查询数据库。问题是我不能让一个sql查询保存多个变量。例如。。。在

我可以让这个查询完美地工作。(“wordsofar”是变量名)

c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)

但是我不能让这个代码工作。(“wordsofar”和“noletter”是变量名)

^{pr2}$

它告诉我错误:“error binding parameter 0”

我已尝试重写查询,所以不是“?”它使用了命名约定,如http://docs.python.org/py3k/library/sqlite3.html(大约在页面的一半位置)所示,但这并没有解决问题。在

任何帮助都将不胜感激。谢谢你!在


Tags: 模块答案代码fromexecutesqlwhereselect
2条回答

这一行(您认为行得通)表明wordsofar是一个元素的序列:

c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)

在这种情况下,第二行应该是:

^{pr2}$

如果noletter是一个字符串,wordsofar是一个元组(如您在评论中所说)。在

^{} docs假设第二个参数总是parameters。如果你用“?”那么参数的数目(len(parameters))等于'?'的数目在sql语句中。在

你的代码看起来不错。在

问题出在数据上。wordsofar或noletter都是sqlite3不知道如何存储的对象。在

一种解决方案是对对象进行酸洗。另一个解决方案是提供转换器和适配器功能。在

使用register_adapter注册一个callable,将自定义Python类型类型转换为SQLite支持的类型之一。在

文件还描述了如何提供转换器来处理反向转换:

SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If you want to use other types you must add support for them yourself. The detect_types parameter and the using custom converters registered with the module-level register_converter() function allow you to easily do that.

这是一个相关的SO question with answers。在

相关问题 更多 >