0

I am trying to insert some data from files into a MySQL database. However, while reading a file it shows an error.

This is my code for inserting into the database from files to a MySQL database:

import mysql.connector
import pickle
try:
    connection = mysql.connector.connect(host='localhost',
                                         database='PETROL',
                                         user='Sarthak',
                                         password='q1w2e3r4t5')
    cursor = connection.cursor ( )
    print(connection)
    fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
    pv=[]
    while True :
        try :
            pdate = pickle.load (fp1)
            pv.append(pdate)
        except EOFError :
            for i in pv:
                ins = ("INSERT INTO DATES (Date) VALUES (%(i)s)")
                data ={'i' : i}
                cursor.execute(ins,data)
            fp1.close ()
        connection.commit()
except mysql.connector.Error as error:
    print("Failed to create table in MySQL: {}".format(error))
    cursor.close()
    connection.close()

This kind of error pops up:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "D:\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/sarth/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch.py", line 14, in <module>
    pdate = pickle.load (fp1)
ValueError: peek of closed file

Hagbard
  • 3,430
  • 5
  • 28
  • 64

1 Answers1

0

Since you do not come out of the While loop, and the fp1 pointer has already been closed when dealing with EOFError, you are getting this error.

One way to resolve this would be to break out of the while loop when encountering the EOFError.

So the code becomes:

except EOFError :
            for i in pv:
                ins = ("INSERT INTO DATES (Date) VALUES (%(i)s)")
                data ={'i' : i}
                cursor.execute(ins,data)
            fp1.close ()
            break
ghost
  • 1,107
  • 3
  • 12
  • 31