如何将整个SQL Server表复制到包括列标题的CSV中?

时间:2014-03-07 15:33:17

标签: python sql csv sqlalchemy

摘要

我有一个使用SQLAlchemy连接到SQL Server数据库的Python程序(2.7)。我想将整个SQL表复制到本地CSV文件(包括列标题)。我是SQLAlchemy(版本.7)的新手,到目前为止我能够转储整个csv文件,但我必须明确列出我的列标题。

问题

如何将整个SQL表复制到本地CSV文件(包括列标题)?我不想显式输入我的列标题。原因是如果表的列发生变化,我想避免更改代码。

代码

import sqlalchemy

# Setup connection info, assume database connection info is correct
SQLALCHEMY_CONNECTION = (DB_DRIVER_SQLALCHEMY + '://'
    + DB_UID + ":" + DB_PWD + "@" + DB_SERVER + "/" + DB_DATABASE 
    )
engine = sqlalchemy.create_engine(SQLALCHEMY_CONNECTION, echo=True)
metadata = sqlalchemy.MetaData(bind=engine)
vw_AllCenterChatOverview = sqlalchemy.Table( \
    'vw_AllCenterChatOverview', metadata, autoload=True)
metadata.create_all(engine)
conn = engine.connect()

# Run the SQL Select Statement
result = conn.execute("""SELECT * FROM 
        [LifelineChatDB].[dbo].[vw_AllCenterChatOverview]""")

# Open file 'output.csv' and write SQL query contents to it
f = csv.writer(open('output.csv', 'wb'))
f.writerow(['StartTime', 'EndTime', 'Type', 'ChatName', 'Queue', 'Account',\
    'Operator', 'Accepted', 'WaitTimeSeconds', 'PreChatSurveySkipped',\
    'TotalTimeInQ', 'CrisisCenterKey']) # Where I explicitly list table headers
for row in result:
    try:
         f.writerow(row)
    except UnicodeError:
         print "Error running this line ", row
result.close()

表格结构

在我的示例中,'vw_AllCenterChatOverview'是表格。这是表标题:

StartTime, EndTime, Type, ChatName, Queue, Account, Operator, Accepted, WaitTimeSeconds, PreChatSurveySkipped, TotalTimeInQ, CrisisCenterKey

提前致谢!

1 个答案:

答案 0 :(得分:3)

使用ResultProxy.keys

# Run the SQL Select Statement
result = conn.execute("""SELECT * FROM 
        [LifelineChatDB].[dbo].[vw_AllCenterChatOverview]""")

# Get column names
column_names = result.keys()