0

I was looking for a way to my program to take 2 values from my database, compare them and update or insert some value. I tried in sqlite3 but I didn't find a good solution and I tried on python, but when I run the program, the values are different and never match. I already look on google, here on stack overflow, but didn't find anything.

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

the output whas

('teste',)
teste
não

I wasn't finding a solution for this in sql, that's why I tried with python, but I'm open to listen any other suggestion than python

1
  • Please give us an example of a short input, what output you get, and what output you expect. Commented Sep 7, 2020 at 3:58

2 Answers 2

2

It's a pretty common problem for people unfamiliar with Python/MySQL to run into troubles receiving tuples back from querying. comparacao[0] is a tuple. Tuples are compared lexicographically by element, so you'd have to retrieve the first element (like @Gwyn Evans said) e.g. comparação[0][0] in order to compare it to your string row.

Here is a link to Python docs about comparisons: https://docs.python.org/2.0/ref/comparisons.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this doc is helping me a lot, I was thinking about other situations, this will clarify a lot :)
no problem!!! always glad to help :) python is truly awesome
1

I could be on the wrong track here, but isn't your comparação[0] itself a tuple, so you probably want to be comparing comparação[0][0] with row[0].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.