使用pymssql使导出CSV格式文件

这里是官方例子http://www.pymssql.org/pymssql_examples.html

下面实例程序使用python 2.7运行

# -*- coding: utf-8 -*-
import csv
import pymssql

if __name__ == '__main__':
    sql_st = '''
     SQL语句
    '''

    conn = pymssql.connect(host = '数据服务器地址', user = '用户名', password = '密码', 
    database = '数据库名称')
    cur = conn.cursor()

    cur.execute(sql_st)
    rows = cur.fetchall()
    #如果使用中文则'test.csv'替换成'测试.csv'.decode('utf-8')
    with open('test.csv', 'wb') as f:
        csv_writer = csv.writer(f)
        description = map(lambda x: x[0].encode('gb18030'), cur.description)
        #写入列名        
        csv_writer.writerow(description)
        for row in rows:
            #csv_writer.writerow(row)
            csv_writer.writerow([(x+'\t').encode('gb18030') if isinstance(x, unicode)        else x  for x in row])

    cur.close()
    conn.close()

    print('ok')

 

 

上一篇:Python csv存储


下一篇:JSON