By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,069 Members | 1,249 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,069 IT Pros & Developers. It's quick & easy.

Connection not defined Error in the program

P: 1
Dear All,
I have a problem while data logging in a single table in SQL DB. We are not able to do it. When we are running the python code in raspberry pi we are getting the following error msg.

Program:
Expand|Select|Wrap|Line Numbers
  1. import serial
  2. import time
  3. import MySQLdb as mdb
  4.  
  5. arduino = serial.Serial("/dev/ttyACM0")
  6. arduino.baudrate=9600
  7.  
  8. data = arduino.readline()
  9. time.sleep(1)
  10. data = arduino.readline()
  11. pieces = data.split("\t")
  12.  
  13. temperature = pieces[0]
  14. humidity = pieces[1]
  15.  
  16. con = mdb.connect('localhost', 'root', '12345678', 'testdb');
  17.  
  18. with con:
  19.  
  20.     cursor = connection.cursor(prepared=True)
  21.     sql_insert_query = """ INSERT INTO TempDB (temperature, humidity) VALUES (?,?)"""
  22.  
  23.     insert_tuple = (temperature, humidity)
  24.     cursor.execute(sql_insert_query, insert_tuple)
  25.     connection.commit()
Error Message

Traceback (most recent call last):
File "./insertDB.py", line 20, in <module>
cursor = connection.cursor(prepared=True)
NameError: name 'connection' is not defined
2 Weeks Ago #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,950
I'm not a Python expert but it looks to me like you added the with con: and forget to remove the connection. at lines 20 and 25.
2 Weeks Ago #2

P: 53
Hi,

You use con variable to store connection string and and use connection variable. so,use con instead of connection.
2 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.