I want to perform an UPDATE? on a SQLite database from Python (2.7). This is the
table`
JavaScript
x
7
1
CREATE TABLE IF NOT EXISTS "foo" (
2
"country_code" TEXT,
3
"country_name" TEXT,
4
"continent_code" TEXT,
5
"area" INTEGER
6
);
7
and this is how I want to insert rows
JavaScript
1
14
14
1
connection = sqlite3.connect('foo.db')
2
cursor = connection.cursor()
3
urlCountriesContinents = 'https://raw.githubusercontent.com/Stophface/geojson-places/master/data/continents/continents.json'
4
countriesContinents = requests.get(urlCountriesContinents)
5
countriesContinents = countriesContinents.json()
6
7
for continent in countriesContinents:
8
continentCode = continent['continent_code']
9
for countryCode in continent['countries']:
10
cursor.execute('UPDATE country SET country_code = ?, country_name = ?, continent_code = ?', (countryCode, 'Foo', continentCode))
11
12
connection.commit()
13
connection.close()
14
However, when I do a SELECT * FROM foo
it the result set
is zero rows.. There is not data in there. Why?
Advertisement
Answer
It sounds like you want to insert here, not update:
JavaScript
1
7
1
for continent in countriesContinents:
2
continentCode = continent['continent_code']
3
for countryCode in continent['countries']:
4
sql = '''INSERT INTO country (country_code, country_name, continent_code)
5
VALUES (?, ?, ?)'''
6
cursor.execute(sql, (countryCode, 'Foo', continentCode))
7
Note that there is a cursor#executeMany()
function which you also might be able to use here, to avoid one/both of the above loops.