SQLite - Run multi-line SQL script from file?

后端 未结 4 674
盖世英雄少女心
盖世英雄少女心 2021-02-01 12:49

I have the following SQL in a file, user.sql:

CREATE TABLE user
(
  user_id INTEGER PRIMARY KEY,
  username varchar(255),
  password varchar(255)
);
相关标签:
4条回答
  • 2021-02-01 13:28

    Here is bernie's python example upgraded to handle exceptions in the script instead of silently failing (Windows 7, ActiveState Python 3.x)

    import sqlite3
    import os
    import os.path
    import ctypes
    
    databaseFile = '.\\SomeDB.db'
    sqlFile = '.\\SomeScripts.sql'
    
    # Delete the old table
    if os.path.isfile(databaseFile):
        os.remove(databaseFile)
    
    # Create the tables
    qry = open(sqlFile, 'r').read()
    sqlite3.complete_statement(qry)
    conn = sqlite3.connect(databaseFile)
    cursor = conn.cursor()
    try:
        cursor.executescript(qry)
    except Exception as e:
        MessageBoxW = ctypes.windll.user32.MessageBoxW
        errorMessage = databaseFile + ': ' + str(e)
        MessageBoxW(None, errorMessage, 'Error', 0)
        cursor.close()
        raise
    
    0 讨论(0)
  • 2021-02-01 13:29

    I realize that this is not a direct answer to your question. As Brian mentions, this could be a silly platform issue.

    If you interface with SQLite through Python, you will probably avoid most platform-specific issues and you get to have fun things like datetime columns :-)

    Something like this should work fine:

    import sqlite3
    
    qry = open('create_table_user.sql', 'r').read()
    conn = sqlite3.connect('/path/to/db')
    c = conn.cursor()
    c.execute(qry)
    conn.commit()
    c.close()
    conn.close()
    
    0 讨论(0)
  • 2021-02-01 13:36

    Multiple lines aren't a problem. There might be a platform issue, because I am able to run this example successfully using SQLite3 3.6.22 on OS X 10.5.8.

    0 讨论(0)
  • 2021-02-01 13:43

    I had exactly the same problem.

    Then I noticed, my editor (Notepad++) reports Macintosh format for end of lines.

    Converting eols into Unix style turned the script file into format, which sqlite3 understood.

    0 讨论(0)
提交回复
热议问题