Python + sqlite:带通配符的LIKE查询 [英] Python+sqlite: the LIKE query with wildcards

查看:70
本文介绍了Python + sqlite:带通配符的LIKE查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我正在尝试基于带有通配符的用户输入来搜索SQlite表.我尝试了不同的方法,但无法正常工作.这是我尝试的最后一件事,实际上是我在这里找到的解决方案,但在python 3中可能已更改.

Hi I'm trying to search an SQlite table based on a user input with wildcards. I've tried different methods by I can't get it to work. This is the last thing I tried, it's a solution I found here actually, but it might have changed in python 3.

    search = input("type name or partial name: ")
    cur.execute("select * from contacts where name like ?",
                ('%'+search+'%'))

这会在该行的最后一行产生此错误.

This produces this error on that last line there.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 5 supplied.

我尝试了很多不同的事情,这使我发疯.我开始认为,如果不首先将整个表读取为字符串,就无法实现.

I tried a lot of different thing and this is driving me crazy. I'm starting to think this isn't possible without reading the entire table to a string first.

推荐答案

您的问题似乎是您提供了一个字符串作为 cur.execute 的第二个参数,而您可能想提供包含字符串的单元素元组.

Your problem just seems to be that you have supplied a string as the second argument to cur.execute, when you probably meant to supply a single-element tuple containing the string.

由于字符串是一个序列,因此字符串中的每个字符都将被解释为一个单独的参数,这就是为什么您看到错误的绑定数"错误的原因.

Since a string is a sequence, every character in the string will be interpreted as a separate parameter and that's why you see the "Incorrect number of bindings" error.

尝试:

cur.execute("select * from contacts where name like ?", ('%'+search+'%',))

请注意元组中的逗号('%'+ search +'%',).没有它,它不是元组,只是括号中的字符串.

Note the comma in the tuple, ('%'+search+'%',). Without it, it isn't a tuple, just a string in parentheses.

这篇关于Python + sqlite:带通配符的LIKE查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆