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.

akhilcjacob
  • 89
  • 3
  • 8
  • Related: [Database does not update automatically with MySQL and Python](http://stackoverflow.com/q/384228/190597) – unutbu Jul 30 '15 at 01:43

2 Answers2

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])
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • the data in the weatherData variable is a list, so would I need to wrap everything with quotes? – akhilcjacob Jul 30 '15 at 01:50
  • @user2672738, I don't understand what you mean. Could you explain by showing the code? – falsetru Jul 30 '15 at 01:52
  • I have the code on github i cleaned up the code a bit but the concept hasn't changed :https://github.com/akhilcjacob/weather_station/blob/master/dataToSQL.py – akhilcjacob Jul 30 '15 at 01:54
  • @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. – falsetru Jul 30 '15 at 02:02
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

acutesoftware
  • 1,091
  • 3
  • 14
  • 33