반응형
/*********************************************************************************************************
-- Title : [Py2.7] sql server 데이터를 csv로 쓰기
-- Reference : gist.github.com/tinybike
-- Key word : pymssql csv
*********************************************************************************************************/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import csv import datetime import pymssql from decimal import Decimal # Connect to MSSQL Server conn = pymssql.connect ('servername', 'username', 'password', 'dbname') # Create a database cursor cursor = conn.cursor() # Replace this nonsense with your own query :) query = """ select top 10 * FROM dbo.ttt with (nolock) where skey > 3555555555555 """ # Execute the query cursor.execute(query) # Go through the results row-by-row and write the output to a CSV file # (QUOTE_NONNUMERIC applies quotes to non-numeric data; change this to # QUOTE_NONE for no quotes. See https://docs.python.org/2/library/csv.html # for other settings options) with open("C:\\samples\\ttt.csv", "w") as outfile: writer = csv.writer(outfile, quoting=csv.QUOTE_NONNUMERIC) for row in cursor: writer.writerow(row) # Close the cursor and the database connection cursor.close() conn.close() | cs |
반응형