user3790497
user3790497

Reputation: 21

Python read query from text file (sqlite3.OperationalError )

I want to read queries from text file. But there are error

    sqlite3.OperationalError: near "DELETE": syntax error

My code is:

    import codecs
    import sqlite3

    conn = sqlite3.connect('D:\\db.sqlite')
    cursor = conn.cursor()

    def main():   
        with codecs.open('D:\\delete.txt','r',encoding='utf8') as myfile:
            cursor.executescript(myfile.read())
            conn.commit()
        conn.close()

    if __name__ == '__main__' : main()  

My text file is:

    DELETE FROM table1 WHERE  id = 1;
    DELETE FROM table1 WHERE  id = 2;

What is wrong? Please help me

Upvotes: 0

Views: 266

Answers (1)

mhawke
mhawke

Reputation: 87124

Look at the first 3 characters of your file... you'll probably find a UTF8 byte order mark (BOM) there (0xEF, 0xBB, 0xBF).

To remove the BOM, open your file with 'utf-8-sig' encoding:

codecs.open('D:\\delete.txt', 'r', encoding='utf-8-sig')

Upvotes: 1

Related Questions