I am new to Python and trying to connect to the SQL Server db and get the output of query into a flat .txt file.
Some code was working but only close to 1000 records were written and then it stops.
Python version: 2.7.13.
The below code is able to write all 1 million records into csv file not .txt file which is the problem.
import sys
print sys.path
import pyodbc
import pandas as pd
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=HCR046TW5SQL\HCRMIG50016;DATABASE=ENT;UID=pmatsa1;PWD=password@2015_1711;autocommit=True')
print 'Trying to assign cursor connection'
cursor = connection.cursor()
sql = """SELECT
LEFT(ltrim(ISNULL(IN_OUT_BUILDING_NUM,' '))+REPLICATE(' ', 10) , 10)+
LEFT( ltrim(ISNULL(IN_OUT_ADR_ORIG_SHORT,' '))+REPLICATE(' ', 50) , 50)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_CITY,' '))+REPLICATE(' ', 28) , 28)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_STATE,' '))+REPLICATE(' ', 2) , 2)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_ZIP,' '))+REPLICATE(' ', 9) , 9)
FROM ADDR_VAL_STAN_PB;"""
DataOut = open("Address_Validation_Input_File.txt", "a+")
cursor.execute(sql)
# Get data in batches
while True:
# Read the data
df = pd.DataFrame(cursor.fetchmany(1000))
# We are done if there are no data
if len(df) == 0:
break
# Let's write to the file
else:
df.to_csv(DataOut, header=False)
# Clean up
DataOut.close()
cursor.close()
connection.close()