如何使用Python将SQL Server查询输出写入.txt文件?

时间:2018-01-24 18:26:28

标签: python sql-server flat-file

我是Python新手并尝试连接到SQL Server数据库并将查询输出转换为平面.txt文件。

有些代码正在运行,但只写了近1000条记录,然后就停止了。

Python版本:2.7.13。

以下代码能够将所有100万条记录写入csv文件而不是.txt文件,这就是问题所在。

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()

1 个答案:

答案 0 :(得分:0)

将以下代码替换为代码中while下面的代码:

df_csv=pd.DataFrame()
while True:
# Read the data
     df = pd.DataFrame(cursor.fetchall())
     # We are done if there are no data
     if len(df) == 0:
            break
     # Let's write to the file
     else:
          df_csv.append(df)
df_csv.to_csv('D:/path/test.txt', header=None, index=None, sep=' ', mode='a')