1

I am trying to retrieve an ongoing insert script from SQL Server using python and output the data one by one every 3seconds. Please help a noobie here!

However, I am getting the error message:

Nothing in database
name 'prev_id' is not defined

Any ideas why?

import time
sql_conn = connectSQLServer('ODBC Driver 13 for SQL Server', 'DESKTOP\SQLEXPRESS', 'display')

mycursor = sql_conn.cursor()
global prev_id
a = 0
d = { 'x': [], 'y': [] ,'z': []  , 'a':[] }
while True:
    try:
        time.sleep(3)
        a=a+1
        print(a)
        sql = "SELECT ID,position ,action ,sync FROM dbo.data2 WHERE ID > %s" % (prev_id)
        mycursor.execute(sql) 
        myresult = mycursor.fetchall()
        #d = { 'x': [], 'y': [] }
        for x in myresult:
            print(x)
            prev_id = x[0]
            d['x'].append(x[0])
            d['y'].append(x[1])
            d['z'].append(x[2])
            d['a'].append(x[3])
        df = pd.DataFrame(d)

    except Exception as error:
        print("Nothing in database\n")
        print(error)
sql_conn.commit()

1 Answer 1

2

You are getting the error message because you have not assigned any value to the prev_id variable before you use it the first time. Presumably you would want to assign it to 0 or something equivalent.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.