简体   繁体   English

如何使用 Python 中的变量搜索 SQLite3 DB

[英]how to search SQLite3 DB using a variable in Python

I'm currently writing a program in Python which I need to search a SQLite3 database, I want to be able to search the DB using a variable, which I will get data for the variable from a Tkinter Combobox selection (GUI)我目前正在用 Python 编写一个程序,我需要搜索 SQLite3 数据库,我希望能够使用变量搜索数据库,我将从 Tkinter 组合框选择(GUI)中获取该变量的数据

Below is my table code...下面是我的表代码...

db = sqlite3.connect('db.sqlite3')
cursor = db.cursor()
cursor.execute('''
            CREATE TABLE IF NOT EXISTS depot_racks(
                id INTEGER PRIMARY KEY,
                rack TEXT,
                rackloc TEXT,
                floorzone TEXT,
                product TEXT,
                serial TEXT,
                status TEXT,
                entdate TEXT,
                servdate TEXT,
                parts TEXT,
                pat TEXT)''')

Below is my code for trying to search the DB using the variable which gets the users selection...下面是我尝试使用获取用户选择的变量搜索数据库的代码...

def search_all_racks():
    selection = rackTextBox.get()
    cursor.execute("SELECT * FROM depot_racks WHERE product LIKE '%selection%'")
    for row in cursor.fetchall():
        dataArea.insert('end', row)

This returns nothing, is there a way to use the selection variable inside the SQLite query?这不返回任何内容,有没有办法在 SQLite 查询中使用selection变量?

Thanks in advance提前致谢

You are using the string literal 'selection' and not the value of the variable selection .您正在使用字符串文字'selection'而不是变量selection的值。
This is the correct way to do it:这是正确的做法:

cursor.execute("SELECT * FROM depot_racks WHERE product LIKE '%' || ? || '%'", (selection,))

This way the wildcards % will be concatenated with the value of the string selection .这样通配符%将与字符串selection的值连接起来。

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

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