Script en Python para exportar consultas de SQL Server a un archivo de texto

Requisitos

Windows

Microsoft ODBC Driver 18 for SQL Server - https://learn.microsoft.com/es-es/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver16#download-for-windows

Alpine

Buscar la versión de Microsoft ODBC Driver a instalar y descargarla. https://learn.microsoft.com/es-es/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver16#alpine
curl -O https://download.microsoft.com/download/3/5/5/355d7943-a338-41a7-858d-53b259ea33f5/msodbcsql18_18.3.3.1-1_amd64.apk
apk add --allow-untrusted msodbcsql18_18.3.3.1-1_amd64.apk
/etc/odbc.ini
[ODBC Driver 18 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18.3.so.3.1
UsageCount=1

Python

pip install --upgrade pip
pip install pyodbc

Código

import pyodbc

#https://learn.microsoft.com/es-es/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver16#download-for-windows

connectionString = f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER=localhost;DATABASE=prueba;UID=sa;PWD=contraseña;TrustServerCertificate=yes;'

conn = pyodbc.connect(connectionString) 


SQL_QUERY = "SELECT  GETDATE() AS col1;"

cursor = conn.cursor()
cursor.execute(SQL_QUERY)

fout = open('query.txt','w', encoding="utf-8")

for r in cursor.fetchall():
    fout.write(f'{r.col1}\n')

fout.close()
cursor.close()
conn.close()

Comentarios

Entradas más populares de este blog

Reinicio de asignación de puertos en Windows

Prompt negativo - Stable Diffusion

Instalación de insightface para ComfyUI