Connection not defined Error in the program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rithik
    New Member
    • Jun 2020
    • 1

    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.

    Program:
    Code:
    import serial
    import time
    import MySQLdb as mdb
    
    arduino = serial.Serial("/dev/ttyACM0")
    arduino.baudrate=9600
    
    data = arduino.readline()
    time.sleep(1)
    data = arduino.readline()
    pieces = data.split("\t")
    
    temperature = pieces[0]
    humidity = pieces[1]
    
    con = mdb.connect('localhost', 'root', '12345678', 'testdb');
    
    with con:
       
        cursor = connection.cursor(prepared=True)
        sql_insert_query = """ INSERT INTO TempDB (temperature, humidity) VALUES (?,?)"""
    
        insert_tuple = (temperature, humidity)
        cursor.execute(sql_insert_query, insert_tuple)
        connection.commit()
    Error Message

    Traceback (most recent call last):
    File "./insertDB.py", line 20, in <module>
    cursor = connection.curs or(prepared=Tru e)
    NameError: name 'connection' is not defined
    Last edited by Banfa; Jun 23 '20, 09:16 AM. Reason: Added code tags
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • AjayGohil
      New Member
      • Apr 2019
      • 83

      #3
      Hi,

      You use con variable to store connection string and and use connection variable. so,use con instead of connection.

      Comment

      • shkum
        New Member
        • Aug 2022
        • 1

        #4
        I got same error when tried to connect to DB wich was not yet created

        Comment

        • sandrahdes
          New Member
          • Sep 2022
          • 1

          #5
          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.

          Comment

          Working...