2013-10-29 22 views
0

我需要在表格末尾添加一個額外的列。如何在python腳本中添加列到表中?

我有一個python腳本,一個(現在失蹤)的開發人員爲我做了,但我無法添加一列和成功添加數據。

有人可以幫助我,告訴我究竟哪裏需要改變?

我試圖在piLongitude real之後在模式, piNew text上添加,但是當我運行它時,數據未加載到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() 
+0

打印所有'c.execute'參數以查看它們是否正確。 – furas

+0

你是如何計算piNew領域的價值的?它應該在你的輸入csv中嗎?你是否基於其他運行時數據來計算它?我敢打賭,你的輸入沒有額外的列,所以你在每個插入到PI的時候都會失敗,因爲你沒有提供足夠的值來滿足表中的所有必填字段。 PI_rtree表是否被創建並正確填充? –

回答

0

在這種情況下,它只是在表的末尾添加列沒有奏效,但在此之前的座標字段。

我沒有解釋,但嘗試和工作,無需改變腳本上的任何其他內容。