Skip to content

Instantly share code, notes, and snippets.

@garyjoy
Created October 16, 2015 03:12
Show Gist options
  • Save garyjoy/920b3cfdc2c9a7be2bb2 to your computer and use it in GitHub Desktop.
Save garyjoy/920b3cfdc2c9a7be2bb2 to your computer and use it in GitHub Desktop.
import argparse
import pypyodbc
import sys
from SomeClass import retrieveCredentials, resultsToXml, appendToFile
def executeScript(database, script, outputFilePath):
"""
Execute the specified (SQL) --script against the specified --database and save the results (as XML) using the specified --outputFilePath
:param database:
:param script:
:param outputFilePath:
"""
user, password = SomeClass.retrieveCredentials(database)
connectionString = "DRIVER={myDriver};DBCNAME=" + database + ";UID=" + user + ";PWD=" + password + ";"
connection = pypyodbc.connect(connectionString)
with open(script, "r") as scriptFile:
commandsString = scriptFile.read()
myCursor = connection.cursor()
commands = commandsString.split(";\n")
for command in commands:
if command and len(command) > 0:
myCursor.execute(command)
if myCursor.rowcount > 0 and myCursor.description:
myData = myCursor.fetchall()
xmlString = SomeClass.resultsToXml(myData)
SomeClass.appendToFile(outputFilePath, xmlString)
connection.close()
def parseArguments(args):
parser = argparse.ArgumentParser(description="Execute the specified (SQL) --script against the specified --database and save the results (as XML) using the specified --outputFilePath", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--database", required=True, help="Database Name")
parser.add_argument("-s", "--script", required=True, help="SQL Script")
parser.add_argument("-o", "--outputFilePath", required=True, help="Output File (XML)")
arguments = parser.parse_args(args)
return arguments
if __name__ == "__main__":
arguments = parseArguments(sys.argv[1:])
executeScript(arguments.database, arguments.script, arguments.outputFilePath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment