471,321 Members | 1,746 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,321 software developers and data experts.

Connection not defined Error in the program

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.

Expand|Select|Wrap|Line Numbers
  1. import serial
  2. import time
  3. import MySQLdb as mdb
  5. arduino = serial.Serial("/dev/ttyACM0")
  6. arduino.baudrate=9600
  8. data = arduino.readline()
  9. time.sleep(1)
  10. data = arduino.readline()
  11. pieces = data.split("\t")
  13. temperature = pieces[0]
  14. humidity = pieces[1]
  16. con = mdb.connect('localhost', 'root', '12345678', 'testdb');
  18. with con:
  20.     cursor = connection.cursor(prepared=True)
  21.     sql_insert_query = """ INSERT INTO TempDB (temperature, humidity) VALUES (?,?)"""
  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
Jun 23 '20 #1
4 18760
9,065 Expert Mod 8TB
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.
Jun 23 '20 #2
83 64KB

You use con variable to store connection string and and use connection variable. so,use con instead of connection.
Jun 24 '20 #3
1 Bit
I got same error when tried to connect to DB wich was not yet created
4 Weeks Ago #4
1 Bit
When we try to access a variable or function that is not defined or before it is defined, Python throws the error "NameError: name is not defined." Make sure the variable's name is spelled correctly and access it after it has been defined to fix the issue. Here is an illustration of the fallacy in action. When a variable, function, or module is used in Python but either doesn't exist or wasn't used properly, a NameError is raised. Common errors that lead to this error include the following: using a name for a variable or function that hasn't yet been declared.
3 Weeks Ago #5

Post your reply

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

Similar topics

6 posts views Thread by beav At wn DOT com DOT au | last post: by
6 posts views Thread by Chris Szabo | last post: by
reply views Thread by May | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.