简体   繁体   English

根据python变量的值从表中检索数据

[英]retrieving data from table based on a value from a python variable

I am writing a function that will retrieve data from sqlite table based on the parameters user provide. 我正在编写一个函数,它将根据用户提供的参数从sqlite表中检索数据。 This is the function so far 这是到目前为止的功能

def database_retrieve(db_file, id):
    try:
        conn = sqlite3.connect(db_file)

        with conn:
            sql_command = "SELECT * FROM my_table WHERE id = "+id

            cur = conn.cursor()
            cur.execute(sql_command)
            result = cur.fetchall()

            return result

    except Exception as e:
        print(e)

db_file = 'testdb.db'
print(database_retrieve(db_file, 'subject1'))

This gives me the following error 这给我以下错误

no such column: subject1
None

When I add subject1 , which is an entry under the id column in my_table , directly to the sql command like this 当我将subject1 (这是my_tableid列下的条目)直接添加到sql命令时,就像这样

sql_command = "SELECT * FROM my_table WHERE id = 'subject1'"

it works fine and prints all the data. 它工作正常并打印所有数据。

I am new to sqlite3. 我是sqlite3的新手。 Please help. 请帮忙。 Thanks in advance 提前致谢

These are the links I used to come this far Python sqlite3 string variable in execute 这些是我用来执行到目前为止的Python sqlite3字符串变量的链接

https://www.dummies.com/programming/databases/how-to-retrieve-data-from-specific-rows-in-mysql-databases/ https://www.dummies.com/programming/databases/how-to-retrieve-data-from-specific-rows-in-mysql-databases/

When you do this 当你这样做

sql_command = "SELECT * FROM my_table WHERE id = "+id

The value of sql_command is sql_command的值为

"SELECT * FROM my_table WHERE id = subject1"

As you can see, subject1 is not in quotes. 如您所见, subject1不在引号中。 sqlite thinks it is a column, that's why you see that error. sqlite认为这是一列,这就是为什么您看到该错误。

Instead, do this 而是这样做

sql_command = "SELECT * FROM my_table WHERE id = ?"
cur.execute(sql_command, [id])

? acts as a placeholder for the variable id . 充当变量id的占位符。

The official sqlite3 documentation mentions few others methods https://docs.python.org/2/library/sqlite3.html sqlite3官方文档提到了其他一些方法https://docs.python.org/2/library/sqlite3.html

生成的sql_command字符串应类似于以下内容(格式化字符串):

sql_command = "SELECT * FROM my_table WHERE id = %s AND name = %s" % (212212, 'shashank')

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

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