0
def quantity():
    i = 0
    x = 1

    file = open("john.txt", "r")

    while i < 5000:

        for line in file:
            c.execute("INSERT INTO test (playerNAME, playerID) VALUES ("+line+", "+str(x)+")")
            conn.commit()

            x = random.randint(100,10000000000000000)
            i += 1

I try to iterate through the John.txt file and insert each value into a table. The first word in the txt file is "abc123". When I run this code there is an error: sqlite3.OperationalError: no such column: abc123

I can get the code to enter the random numbers into playerID but I can't get the txt file query to work...

2
  • you are missing the quotes around line: VALUES ('"+line+"', "+str(x)+")") Commented Apr 25, 2016 at 16:12
  • 1
    Never concat sql queries and strings. Use the parameterized version of execute. Commented Apr 25, 2016 at 16:22

2 Answers 2

1

You need single quotes around the string.

c.execute("INSERT INTO test (playerNAME, playerID) VALUES ('"+line+"', "+str(x)+")")

Otherwise it tries to interpret it as a sql expression and looks for the named column.

More generally you should use parameters or sanitize the incoming data from the file for safety against sql insertion. Even if you trust this particular file. It's a good habit.

c.execute("INSERT INTO test (playerName, playerID) VALUES (?, ?)", (line, x))

Details are here and here is why it's important.

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

2 Comments

Could you explain what you mean by using parameters to sanitize...? I don't understand. Thanks for the answer by the way!
If playerID is string type, rather than a numeric type you'd them around the second parameter as well. You can also just try the parametrized version as well which I added.
1

Formatting sql queries via string concatenation is very bad practice. Variable bindging should always be used:

c.execute("INSERT INTO test (playerNAME, playerID) VALUES (?, ?)", [line, x])

In your case the line probably contains spaces or any punctuation mark. The sqlite's error string is misleading, though.

2 Comments

Why is this method better practice?
@Dominico909 Because your line may contain some sql and it will be executed. Consider : DROP TABLE blahbla

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.