简体   繁体   中英

how to execute .sql file using pyodbc connection

I have a folder which contains SQL files. I want to execute all these SQL files using a pyodbc connection.

I tried different ways but I am still facing some issues. My code looks like below.

import os
import pyodbc

conn =  pyodbc.connect('Driver=ODBC Driver 17 for SQL Server;'
                      'Server=SIS10647\MSSQLSERVER14;'
                      'Database=LeelaVenkatesh;'
                      'Trusted_Connection=yes;')


inputdir = 'C:\SCM\pyodbc'

for script in os.listdir(inputdir):
    with open(inputdir+'\\' + script,'r') as inserts:
        sqlScript = inserts.readlines()
        for statement in sqlScript.split(';'):
            with conn.cursor() as cur:
                cur.execute(statement)
    print(script)

conn.close()

The error I am getting as follows

AttributeError: 'list' object has no attribute 'split'

Don't use readlines , use read . read brings in the whole file as one string, so you can split it on the semicolons. readlines splits the file into lines, and returns a list of lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM