Run multiline SQL script from file?

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

CREATE TABLE user ( user_id INTEGER PRIMARY KEY, username varchar(255), password varchar(255) ); 

However, when the following command is executed:

 sqlite3 my.db < user.sql 

The following error is generated:

 Error: near line 1: near ")": syntax error 

I would prefer to save SQL as-is, as the file will be checked in the original control and will be more convenient and readable, as it is now. Can SQL span multiple rows like this, or do I need to put all this on one line?

+46
scripting sqlite
Mar 04 '10 at 15:43
source share
4 answers

I had exactly the same problem.

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

Converting eols to Unix style turned the script file into a format that sqlite3 understood.

+22
Feb 07 2018-12-12T00:
source share

I understand that this is not a direct answer to your question. As Brian mentions, this can be a dumb platform issue.

If you interact with SQLite through Python, you will probably avoid most of the platform-related issues and you will enjoy 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() 
+19
Mar 04
source share

A few lines are not a problem. There may be a platform issue because I can successfully run this example using SQLite3 3.6.22 on OS X 10.5.8.

+2
Mar 04 '10 at 16:01
source share

Here's an example of bernie python to handle exceptions in a script instead of silent failure (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 
+1
Aug 05 2018-12-12T00:
source share



All Articles