0

I'm trying to test a small piece of code I wrote to search a column of a table for a specific string. The code should search the Users column of the LoginInfo table and print out the result. I have tried two versions of this code but both get different errors.

VERSION ONE:

    import sqlite3
    import sys
    Username = "('Hello1',)"
    print(Username)

    connection= sqlite3.connect("Logininfo.db")
    c = connection.cursor() 

    c.execute('''SELECT Username FROM LoginInfo WHERE Username=Hello1''') 
    for row in c :
        print(row)

VERSION ONE ERROR:

c.execute('''SELECT Username FROM LoginInfo WHERE Username=Hello1''') sqlite3.OperationalError: no such column: Hello1

VERSION TWO:

    import sqlite3
    import sys
    Username = "('Hello1',)"
    print(Username)

    connection= sqlite3.connect("Logininfo.db")
    c = connection.cursor() 

    c.execute("SELECT Username FROM LoginInfo WHERE Username="Hello1"") 
    for row in c :
        print(row)

VERSION TWO ERROR:

Invalid syntax error pop up highlighting Hello1

Any help would be appreciated as I'm really new at this.

1 Answer 1

2

You have problems with your syntax in both cases. When you send a string into cursor.execute you are sending the DB a complete command. This means strings need to be quoted correctly, SQL syntax needs to be correct, etc.

This command: SELECT Username FROM LoginInfo WHERE Username=Hello1 means:

"Give me the Username column from the LoginInfo table where Username matches the Hello1 column"

On the other hand this command: SELECT Username FROM LoginInfo WHERE Username='Hello1' (note the quotes) means:

"Give me the Username column from the LoginInfo table where Username = Hello1"

Your second attempt is simply invalid Python. You should be using triple quotes on the outside or escaping the quotes that are part of the query.

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

2 Comments

I have tried doing this, is this what you mean? I get an error EOL while scanning string literally. c.execute("""SELECT Username FROM LoginInfo WHERE Username = "Hello1"""")
Suspect you need to be using single quotes around Hello1.=: c.execute("""SELECT Username FROM LoginInfo WHERE Username = 'Hello1'""")

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.