2014-02-11 19 views
-2

我希望寫一個python腳本,檢查數據庫表中的特定列,如果它不存在,添加它,這可能嗎?如果有的話,是否有任何文件指出我正確的方向? 在此先感謝!一個python腳本檢查,如果數據庫表列中存在

+3

你可以發佈你試過嗎? – IanAuld

+0

您是否試過使用Google搜索? –

+0

見[這裏](https://www.google.ca/search?q=python+script+which+checks+if+a+database+table+column+exists&oq=python+script+which+checks+if+一個+數據庫+表+柱+存在&AQS = chrome..69i57j69i64.2094j0j7&的SourceID =鉻&espv = 210&es_sm = 122&即= UTF-8) – jramirez

回答

1

一旦你連接到使用MySQLdb的一臺機器的數據庫,並創建光標,你可以先執行下面的查詢。

import MySQLdb 

conn = MySQLdb.connect(host='localhost', db='test', user='root') 
cursor = conn.cursor() 

cursor.execute("select * from information_schema.COLUMNS where table_name = 'table-name' and column_name = 'column-name' ") 

_filed = cursor.fetchall() 

if len(_filed) == 0, u can execute another alter query to add the column 

cursor.execute('alter table table-name add column <column-name> int(11) default 0') 
相關問題