I have a school project for a Python script which runs an SQL query and spits out results to a file… I have this so far and wanted some feedback on if this looks right or if I am way off (I’m using adodbapi). Thanks much!
import adodbapi
# Connect to the SQL DB
conn = adodbapi.connect("Provider=SQLDB;SERVER= x.x.x.x ;User Id=user;Password=pass;DATABASE=db database;")
curs = conn.cursor()
# Execute SQL query test_file.sql"
query = 'test_file'
curs.execute("SELECT test_file")
rows = curs.fetchall()
for row in rows:
print test_file | test_file.txt
conn.close()
# Execute SQL query test_file.sql"You are not executing an SQL query from a file. You are executing the SQL query"SELECT test_file"."SELECT test_file"is not valid SQL syntax for theSELECTquery. See this tutorial on theSELECTstatement.rows = curs.fetchall(); for row in rows: ...is not a nice way of iterating through all the results of a query.The more Pythonic way of doing this is to avoid loading the entire data set into memory unless you have to. Using
sqlite3I would write:This way only one row is loaded at a time.
print test_file | test_file.txt: theprintstatement does not support the pipe operator for writing to a file. (Python is not a Linux shell!) See Python File I/O.Additionally, even if this syntax was correct, you have failed to put the file name in
'quote marks'. Without quotes, Python will interprettest_file.txtas the propertytxtof a variable calledtest_file. This will get you aNameErrorbecause there is no variable calledtest_file, or possibly anAttributeError.If you want to test your code without having to connecting to a network database, then use the
sqlite3module. This is a built-in library of Python, implementing a database similar toadodbapi.In future please try running your code, or at least testing that individual lines do what you expect. Trying
print test_file | test_file.txtin an interpreter would have given you aTypeError: unsupported operand type(s) for |: 'str' and 'str'.