2015-09-05 63 views
1

我寫走線在SQL數據庫中,當它不存在,自動添加一列,如果附加表(蟒蛇熊貓)

但有時候有一個新的特點,就是還沒有在列SQL數據庫,所以我得到一個錯誤。

有沒有辦法將一行寫入SQL,並自動添加一個新的列,如果它不存在?

+0

需要更改表中添加列。 http://stackoverflow.com/a/2614737/4080476 –

+0

這可以在SQL中完成,如果不存在... else ..或case語句。 – 2015-09-05 13:14:14

回答

0

使用Python,你可以這樣做:

def add_column_to_table(c, table_name, column_name, column_type): 
    for row in c.execute('PRAGMA table_info({})'.format(table_name)): 
     if row[1] == column_name: 
      # print('column {} already exists in {}'.format(column_name, table_name)) 
      break 
    else: 
     # print('add column {} to {}'.format(column_name, table_name)) 
     c.execute('ALTER TABLE {} ADD COLUMN {} {}'.format(table_name, column_name, column_type)) 

c = db.cursor() 
add_column_to_table(c, 'mytable', 'newcolumn', 'INTEGER')