0

I have constructed a database but when I loop through my data to populate it, I get the following error:

OperationalError: no such column: tmp1

Code:

with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE TESTTABLE(X REAL, Y REAL)")

for i in xrange(0,5):
   tmp1 =  array[i,0]
   tmp2 =  array[i,1]
   with con:
        cur.execute("""INSERT INTO TESTTABLE VALUES(tmp1,tmp2)""")

Basically I have a big array that I want to transfer into a database. This probably isn't the most efficient way of going about it. Suggestions?

1 Answer 1

2

If you want to insert values into a row, you need to pass those values along as SQL parameters to the .execute() call:

with con:
    for i in xrange(0,5):
        tmp1 = array[i, 0]
        tmp2 = array[i, 1]
        cur.execute("""INSERT INTO TESTTABLE VALUES(?, ?)""", (tmp1, tmp2))

The ? characters are parameters, and they are filled, in order, by values takes from the second argument to .execute(), a tuple. The above code will insert the numbers 0 through to 4 as pairs into the database.

Names in the SQL code have no correlation to names you define in Python, values can only be passed in explicitly.

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

3 Comments

So do I replace the ? with the variable names I assigned, (X,Y) as well? Could you edit your answer to show how cur.execute("""INSERT INTO TESTTABLE VALUES(tmp1,tmp2)""") should be changed. cur.execute("""INSERT INTO TESTTABLE VALUES(?,?)""",(tmp1,tmp2)) doesn't work.
I'm inserting the value of an array element, not the entire array.
@Griff: Can you elaborato on why my answer "doesn't work" for you? What types are tmp1 and tmp2 here? What is the error that you receive?

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.