【问题标题】:Comparing SQL results with Python将 SQL 结果与 Python 进行比较
【发布时间】:2020-09-06 16:06:47
【问题描述】:

我正在寻找一种方法让我的程序从我的数据库中获取 2 个值,比较它们并更新或插入一些值。 我在sqlite3中尝试过,但没有找到好的解决方案,我在python上尝试过,但是当我运行程序时,值不同并且永远不匹配。我已经在谷歌上看过,这里是堆栈溢出,但没有找到任何东西。

cursor.execute("select * from [Sistema]")
Teste = cursor.fetchall()
cursor.execute("select [SistemaOperacional] from [Sistema] where [SistemaOperacional] = 'teste'")
comparacao = cursor.fetchall()
testando = comparacao
for row in Teste:
    #I was checking the values to see if they where equal
    print(comparação[0]) #Value ('teste',)
    print(row[0]) #Value 'teste'
    if row[0] == comparação[0]:
        cursor.execute("Update [Sistema] set [SistemaOperacional] = '1' where [VersaoBanco] = 3")
        print('Executado')
        break
    else:
        cursor.execute("insert into [Sistema] values ('9','9','1')")
        print('não')
        break

输出是什么

('teste',)
teste
não

我没有在 sql 中找到解决方案,这就是我尝试使用 python 的原因,但我愿意听取除 python 之外的任何其他建议

【问题讨论】:

  • 请给我们一个简短输入的例子,你得到什么输出,你期望什么输出。

标签: python sql python-3.x sqlite


【解决方案1】:

对于不熟悉 Python/MySQL 的人来说,在从查询中接收元组时遇到问题是一个很常见的问题。 comparacao[0] 是一个元组。元组按字典顺序按元素进行比较,因此您必须检索第一个元素(如@Gwyn Evans 所说),例如comparação[0][0] 以便将其与您的字符串 row 进行比较。

这里是关于比较的 Python 文档的链接:https://docs.python.org/2.0/ref/comparisons.html

【讨论】:

  • 谢谢,这个文档对我帮助很大,我在考虑其他情况,这会澄清很多:)
  • 没问题!!!总是很乐意提供帮助 :) python 真的很棒
【解决方案2】:

我在这里可能走错了路,但您的 comparação[0] 本身不是一个元组,所以您可能希望将 comparação[0][0]row[0] 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多