python无限循环中的sqlite3

时间:2016-10-11 13:18:55

标签: sql python-3.x loops sqlite

这是使用table创建数据库的代码:

import sqlite3

con = sqlite3.connect('testcountry.db3')
cur = con.cursor()

cur.execute('create table if not exists my_table(city varchar, country varchar, status varchar);')
cur.execute('insert into my_table (city, country, status) values ("New York", "USA", null);')
cur.execute('insert into my_table (city, country, status) values ("Los Angeles", "USA", null);')
cur.execute('insert into my_table (city, country, status) values ("Houston", "USA", null);')
cur.execute('insert into my_table (city, country, status) values ("Dallas", "USA", null);')
cur.execute('insert into my_table (city, country, status) values ("Miami", "USA", null);')
cur.execute('insert into my_table (city, country, status) values ("Toronto", "Canada", null);')
cur.execute('insert into my_table (city, country, status) values ("Montreal", "Canada", null);')


con.commit()

con.close()

以下是我要执行的代码:

import sqlite3

list_of_countries = ['USA', 'Canada']

con = sqlite3.connect('testcountry.db3') 
con.row_factory = lambda cursor, row: row[0]
cur = con.cursor()

percentage = [cur.execute('select round(count(status) * 100 / count(country), 5) from my_table where country is ?;', (x,)).fetchone() for x in list_of_countries]
print(percentage)

for i,v in enumerate(list_of_countries):

    while percentage[i] < 100:
        print(percentage)


        a = cur.execute('select city from my_table where country is ? and status is null;', (v,)).fetchone()

        b = cur.execute('update my_table set status = "P" where city is ?;', (a,))
        b
        con.commit()



con.close()

这个想法非常简单:

  1. 从列表中获取名称(list_of_countries)
  2. 计算有多少个国家/地区的状态为非空值(获取每个国家/地区的百分比)
  3. 按list_of_countries中的顺序更新状态。一个接一个。
  4. 我面临的问题是:当我运行我的脚本时,它开始循环并且它不会停止。但是它会更新list_of_countries中的第一个值的状态:USA,在这种情况下。

    知道为什么吗?

0 个答案:

没有答案