Skip to content

Instantly share code, notes, and snippets.

@jamescalam
Last active February 26, 2020 17:35
Show Gist options
  • Save jamescalam/586f79e4d9aba64d6e30d70de72d3f90 to your computer and use it in GitHub Desktop.
Save jamescalam/586f79e4d9aba64d6e30d70de72d3f90 to your computer and use it in GitHub Desktop.
def manual(self, query, response=False, comment="manual query",
verbose=False):
"""Enter a manual statement/query.
Keyword arguments:
query -- SQL query to run on SQL connection
response -- Boolean value stating whether a response/table
should be returned (default False)
comment -- string input that translates into a comment in the
self.query string (default "manual query")
verbose -- Boolean value indicating whether to print extra detail to
the terminal or not (default True)
Returns:
if (response=True): a dataframe returned from the query sent
if (response=False): a string to notify user manual query complete
"""
cursor = self.cnxn.cursor() # create execution cursor
# append query to our SQL code logger
self.query += ("\n\n-- "+str(comment)+"\n" + query)
print("Executing query.") # inform user
if verbose:
# print comment and query if user wants
print(comment)
print(query)
if response:
return pd.read_sql(query, self.cnxn) # get sql query
try:
cursor.execute(query) # execute
except pyodbc.ProgrammingError as error:
if verbose:
print("Warning:\n{}".format(error)) # print error as a warning
self.cnxn.commit() # commit query to SQL Server
return "Query complete."
@yizongk
Copy link

yizongk commented Feb 25, 2020

On line 30, where is read_sql() referenced from?

I am getting variable undefined when I try to run manual() with verbose=True

@toconnor9
Copy link

yizongk,
I was able to fix the issue with "read_sql()" by using "pip install pandas" and adding the line "from pandas import read_sql"

@jamescalam
Copy link
Author

Yes toconnor9 is correct, I've updated the code to read pd.read_sql() which should hopefully make it clearer

For anyone needing the class definition it is here

@yizongk
Copy link

yizongk commented Feb 26, 2020

Thank you guys!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment