简体   繁体   English

尝试使用 Python 检查值是否在 sqlite3 中

[英]Trying to check if value is in sqlite3 with Python

I am trying to check if a value is in SQLite with python to then either update the table if the value exists or create a new value if it is not.我正在尝试检查一个值是否在 SQLite 和 python 中,然后如果该值存在则更新表,如果不存在则创建一个新值。 I have tried to create a cursor to check rows, append the rows to a list with loop, check if value exists, check the count of the rows... I seems to get hung up on the if statement when trying to access the value initialized from the query.我试图创建一个 cursor 来检查行,append 将行添加到带有循环的列表中,检查值是否存在,检查行数......我似乎在尝试访问值时挂断了 if 语句从查询初始化。 Here is the code:这是代码:

checkT = db.execute("SELECT COUNT(*) FROM trans WHERE stock=:stock AND id=:user_id", stock=request.form.get("symbol"), user_id=session["user_id"])
if checkT > 0:
            print("there")
else:
            print("not there")

How can I fix this?我怎样才能解决这个问题? Thank you!谢谢!

From the CS50 Library for Python doc for execute来自Python 文档的 CS50 库执行

Returns退货

for SELECTs, a list of dict objects, each of which represents a row in the result set;对于 SELECTs, dict对象的list ,每个对象代表结果集中的一行; for INSERTs, the primary key of a newly inserted row (or None if none);对于 INSERT,新插入行的主键(如果没有,则为 None); for UPDATEs, the number of rows updated;对于 UPDATE,更新的行数; for DELETEs, the number of rows deleted;对于 DELETE,删除的行数; for CREATEs, True on success;对于 CREATE,成功时为真; on error, a RuntimeError is raised出错时,会引发 RuntimeError

checkT is a list with one element, which is a dict with one key/value pair. checkT是一个包含一个元素的list ,它是一个具有一个键/值对的dict

This checkT[0]['COUNT(*)'] will give the number returned from the sql.这个checkT[0]['COUNT(*)']将给出从 sql 返回的数字。 Counting the rows would not be appropriate in this case because this query will always return one row.在这种情况下计算行数是不合适的,因为此查询将始终返回一行。

One hint: column names in a SELECT can be aliased, given a different name, like so:一个提示:SELECT 中的列名可以使用别名,给定一个不同的名称,如下所示:

SELECT COUNT(*) as count from...... . SELECT COUNT(*) as count from...... It would just be typing convenience, because then the key in the returned dict will be count instead of COUNT(*) .这只是打字方便,因为返回的字典中的键将是count而不是COUNT(*)

Remember: in the flask run terminal there is a traceback with gives more details information on the error received (assuming "hung up" means a 500 Internal Server Error).请记住:在flask run终端中,有一个回溯,其中提供了有关收到的错误的更多详细信息(假设“挂起”意味着 500 内部服务器错误)。

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

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