1

want to make small python module that can get data from a database. I have dowload pydbc and it worked fine like this:

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone() 

Now i want to put this in a module so that i can import it and i dont need to write the code evrytime or locate the file. So i tried to create this like this

import pyodbc
def testDB():
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
    cursor = cnxn.cursor()
    cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
    row = cursor.fetchone()    
return row 

I saved it in: File "C:\Python27\lib\site-packages\testDB.py" and i tried to import it, but i got this error: SyntaxError: 'return' outside function

Im quite new to python, any ideas how i can put this as a module and be able to use import everytime i want to run that code?

3
  • 4
    Perhaps you have a return outside of function. Commented Nov 13, 2012 at 21:57
  • 2
    your indention is messed up. Commented Nov 13, 2012 at 22:00
  • On a side note, you might want to investigate sqlalchemy. Commented Nov 13, 2012 at 22:57

1 Answer 1

2

As one of the comments says, your indentation is messed up. White space (indentation) is critical in Python. Try it like this:

import pyodbc
def testDB():
    cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''")
    cursor = cnxn.cursor()
    cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
    row = cursor.fetchone()    
    return row

Also, you have to use double quotes for your connection string, since you are using single quotes in the string itself. I've changed them above in to reflect that.

good luck, Mike

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.