Automatically Load SQL table by reading data from text file

后端 未结 2 834
北海茫月
北海茫月 2021-02-06 19:22

I am trying to write a python script that is going to load the tables that I created in pyhton using SQL and populate them with data automatically that is coming from a text fil

2条回答
  •  北海茫月
    2021-02-06 20:12

    If you can use standard sqlite3 utility, you can do it much easier:

    sqlite3 -init mydata.sql mydatabase.db ""
    

    simply call this line from your python script, and you're done.

    This will read any text file that contains valid SQL statements, and will create mydatabase.db if it did not exist. What's more important, it supports statements spanning more than one line, and also properly ignores SQL comments using both --comment syntax and C/C++ like /*comment*/ syntax.

    Typically your mydata.sql content should look like this:

    BEGIN TRANSACTION;
    CREATE TABLE IF NOT EXISTS table1 (
        id INTEGER PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(32)
    );
    INSERT INTO table1 (name) VALUES
    ('John'),
    ('Jack'),
    ('Jill');
    -- more statements ...
    COMMIT;
    

提交回复
热议问题