简体   繁体   English

来自数据库查询的Python csv将自定义列添加到csv文件

[英]Python csv from database query adding a custom column to csv file

here is what I try to achieve my current code is working fine I get the query to run on my sql server but I will need to gather information from several servers. 这是我尝试实现的当前代码正常运行的方法,我可以在SQL服务器上运行查询,但需要从多个服务器中收集信息。 How would I add a column with the dbserver listed in that column? 如何添加列中包含dbserver的列?

import pyodbc
import csv

f = open("dblist.ini")
dbserver,UID,PWD = [ variable[variable.find("=")+1 :] for variable in f.readline().split("~")]

connectstring = "DRIVER={SQL server};SERVER=" + dbserver + ";DATABASE=master;UID="+UID+";PWD="+PWD

cnxn = pyodbc.connect(connectstring)
cursor = cnxn.cursor()

fd = open('mssql1.txt', 'r')
sqlFile = fd.read()
fd.close()

cursor.execute(sqlFile)


with open("out.csv", "wb") as csv_file:
    csv_writer = csv.writer(csv_file, delimiter = '!')
    csv_writer.writerow([i[0] for i in cursor.description]) # write headers
    csv_writer.writerows(cursor)

You could add the extra information in your sql query. 您可以在sql查询中添加额外的信息。 For example: 例如:

select "dbServerName", * from table;

Your cursor will return with an extra column in front of your real data that has the db Server name. 您的光标将返回,在具有db服务器名称的实际数据之前,会在其前面加上一个额外的列。 The downside to this method is you're transferring a little more extra data. 这种方法的缺点是您要传输更多的额外数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM