1

I'm trying to execute the following code

for counter in range(0, len(weatherData) - 1):
    string = 'INSERT INTO weather VALUES(' + str((weatherData[counter])[0:]) +');'
    print(string)
    cur.execute(string)

All the the values and data are printed correctly and everything seems to work as there is no errors, however when I check the data base its empty.

1

2 Answers 2

1

Do commit after insertion complete.

for counter in range(0, len(weatherData) - 1):
    ....
connection_object.commit()

BTW, you'd better to use parameter-passing style instead of build query string yourself:

for data in weatherData:
    sql = 'INSERT INTO weather VALUES(%s)'
    cur.execute(sql, [data])
Sign up to request clarification or add additional context in comments.

4 Comments

the data in the weatherData variable is a list, so would I need to wrap everything with quotes?
@user2672738, I don't understand what you mean. Could you explain by showing the code?
I have the code on github i cleaned up the code a bit but the concept hasn't changed :github.com/akhilcjacob/weather_station/blob/master/dataToSQL.py
@user2672738, Ah, I got it. You don't need to quote the string. If you pass the string with parameter passing style, db api will care of quoting.
0

The loop can be simplified as follows

for counter, row in weatherData:
    string = 'INSERT INTO weather VALUES(' + str(row) + ');'

and you'll need to commit afterwards

EDIT - added counter, which is a count of the for loop EDIT2 - using row EDIT3 - removed [0:] from end of string which doesn't do anything

1 Comment

row[0:] == row, no need to use [0:] :)

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.