我需要在表的末尾添加一个额外的列。
我有一个(现在失踪的)开发人员为我制作的 python 脚本,但我无法添加列并成功添加数据。
有人可以通过告诉我确切需要更改的地方来帮助我吗?
之后我尝试添加模式, piNew text
,piLongitude real
但是当我运行它时,数据没有加载到 PI 表中。PlacesCovered 表加载成功。
非常感谢!
下面是主要代码:
import codecs
import csv
import sys
import sqlite3
import random, string
import os
import StringIO
schemas = {
'PI':'id integer primary key, piCountry text, piCity text, piType integer, piLatitude real, piLongitude real',
'PlacesCovered':'id integer primary key, pcCountry text, pcCity text, pcName text, pcType text, pcLatitude real, pcLongitude real'}
def main():
if os.path.isfile(DATABASE_NAME):
os.remove(DATABASE_NAME)
db = sqlite3.connect(DATABASE_NAME)
c = db.cursor()
if TEST_DATA:
for name, schema in schemas.items():
make_table(c,name,schema)
add_test_data(c,'PI',TEST_DATA_PI_COUNT,False)
add_test_data(c,'PlacesCovered',5000,True)
else:
for name, schema in schemas.items():
make_table(c,name,schema)
add_data(c,name)
c.execute('create index sort on PlacesCovered(pcCountry,pcType,pcName)');
db.commit()
os.system('open '+PROJECT_PATH)
print('Data imported! Now build and run the app in Xcode.\n')
def make_table(c,name,schema):
c.execute('drop table if exists %s_rtree'%(name))
c.execute('create virtual table %s_rtree using rtree(id,minX,maxX,minY,maxY)'%(name))
c.execute('drop table if exists %s'%(name))
c.execute('create table %s(%s)'%(name,schema))
def make_bounds(lat, lon):
return [lon,lon,lat,lat]
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
def add_data(c, name):
encodings = ["utf-8","iso-8859-1"]
# encodings = ["utf-8"]
# with codecs.open('%s.csv'%(name), "r", "iso-8859-1") as infile:
# normalize newlines
text = None
print("Loading %s.csv..."%(name))
for idx,encoding in enumerate(encodings):
try:
infile = codecs.open('%s.csv'%(name), "r", encoding)
text = infile.read()
break
except IOError as e:
print(e)
break
except UnicodeDecodeError:
if idx == len(encodings)-1:
print("Incompatible character encoding.")
print("Please export your CSVs as UTF-8 or Latin 1 (ISO-8859-1).")
continue
if text is None:
print("Couldn't read %s.csv"%(name))
sys.exit(0)
text = '\n'.join(text.splitlines())
id = 1
sql = u'insert into %s values'%(name)
reader = unicode_csv_reader(StringIO.StringIO(text))
for row in reader:
if row is None or len(row) < 2:
continue
placeholders = ','.join(['?' for field in row])
bounds = make_bounds(row[-2],row[-1]);
c.execute(u'insert into %s values(?, %s)'%(name,placeholders),[id]+row)
c.execute(u'insert into %s_rtree values(?, ?, ?, ?, ?)'%(name),[id]+bounds)
id += 1
def word(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def random_coord(coord):
lat = coord[0] + (random.random()-0.5)*TEST_DATA_RANGE
lon = coord[1] + (random.random()-0.5)*TEST_DATA_RANGE
return [lat,lon]
def add_test_data(c, name, rows, include_name):
id = 1
sql = 'insert into %s values'%(name)
for i in range(rows):
coord = random_coord(TEST_DATA_CENTROID)
row = [word(5),word(5)]
if (include_name):
row = row + [word(5)]
row = row + [random.randint(1,2)]
row = row + coord
# row = ['Country','City','Name','Type','Lat','Lon']
placeholders = ','.join(['?' for field in row])
bounds = make_bounds(row[-2],row[-1]);
c.execute('insert into %s values(?, %s)'%(name,placeholders),[id]+row)
c.execute('insert into %s_rtree values(?, ?, ?, ?, ?)'%(name),[id]+bounds)
id += 1
if __name__ == "__main__":
main()