使用 Python 执行 bcp 将查询从远程服务器导出到本地驱动器

Using Python to execute bcp to export query from remote server to local drive

我有以下 python 组语句。我正在使用 Python 使用动态构建的 SQL 语句。然后将生成的 SELECT 语句用作 BCP 中的 queryout 语句。

我的问题是查询本身太大,BCP 无法操作它。我已经确认 BCP 可以使用:

BCP "Select * from <<DATABASE.dbo.TABLE>>" queryout "D:\data\test.csv" -t^ -r '0x0A' 
    -U <<USER>> -P <<PASSWORD>> -S "LIVE" -c -C65001

但是如果select语句returns一个大数据集,语句失败。我该如何应对? table 很大(超过 100m 条记录),我想做的就是使用动态 SQL 将其从远程服务器导出到本地 table.

Python 脚本:

def getRoster(self):
    self.conn = pyodbc.connect(self.ConnStr)
    sql = r'SELECT * FROM <<DB>>.dbo.TableConfiguration'
    self.roster = pd.read_sql(sql,self.conn)

def GenerateSQL(self, table):
    exportsql = 'select '

    columnsql = """select
                    'CASE WHEN ISNULL('+COLUMN_NAME+', '''') = '''' THEN '''' ELSE '+COLUMN_NAME+' END AS '+UPPER(COLUMN_NAME)
                    from <<DB>>.INFORMATION_SCHEMA.COLUMNS
                    where TABLE_NAME = '%s'
                    order by ORDINAL_POSITION""" % table.tablename
    self.conn = pyodbc.connect(self.ConnStr)
    cursor = self.conn.cursor()
    cursor.execute(columnsql)
    exportsql += ', '.join([field[0] for field in cursor])
    exportsql += ' from {}.dbo.{}'.format(table.dbname, table.tablename)
    exportsql += ' {}'.format(table.Clause)
    return (exportsql)

def ExportTables(self):
    now = datetime.now()
    self.getRoster()
    for row in self.roster.itertuples():
         SQL = self.GenerateSQL(row)
         self.filename = '{}_{}.csv'.format(row.tablename, now.strftime("%Y-%m-%d"))
         command = 'BCP \"{}\" queryout \"{}\" -t|| -U "<<USER>>" -P <<PASSWORD>> -S "LIVE" -T -r 0x0a -c -C65001'.format(SQL, os.path.join(self.path, self.filename))
         print (command)
         subprocess.run(command)

当使用 SELECT 'test' 测试 bcp 时,它恢复正常。但是当生成sql时,sql在SMSS中有效,但在bcp中,错误是:

SQLState = 28000, NativeError = 18452
Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentic
ation.

从您的 BCP 命令行中删除 -T 参数并使用 SQL 服务器身份验证。

bcp Utility - T

When the bcp utility is connecting to SQL Server with a trusted connection using integrated security, use the -T option (trusted connection) instead of the user name and password combination. When the bcp utility is connecting to SQL Database or SQL Data Warehouse, using Windows authentication or Azure Active Directory authentication is not supported. Use the -U and -P options.