Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute sqlite3 "dot" commands from Python or register collation in command line utility

Tags:

My sqlite3 database contains a "collate" column-constraint. I've placed it in the schema for the table, to prevent accidentally neglecting to use the necessary collation. However this means when running sqlite3 from the command line, and not from my Python code, the collation referenced in the schema is not present, and I'm unable to use dot commands.

sqlite> .import data.txt table_name Error: no such collation sequence: my_collation 

Furthermore, creating the connection from Python, and adding the collation required runs into this problem:

connWithCollation.execute(".import data.txt table_name") Traceback (most recent call last):   File "<stdin>", line 1, in <module> sqlite3.OperationalError: near ".": syntax error 

The execute function it would appear does not want to pass the sqlite3 dot command through.

How can I execute sqlite3 dot commands when necessary collation functions are not present? Alternatively, how can I execute sqlite3 dot commands from Python?

like image 279
Matt Joiner Avatar asked Feb 27 '10 03:02

Matt Joiner


People also ask

How do I run a SQLite client from command line?

If you are using Linux or a Mac, open a terminal window instead a command prompt. Open a command prompt (cmd.exe) and 'cd' to the folder location of the SQL_SAFI. sqlite database file. run the command 'sqlite3' This should open the SQLite shell and present a screen similar to that below.


2 Answers

You can call dot commands from Python using the subprocess module, which basically invokes a shell. If you need to use multiple dot commands, you can pass them as separate shell arguments - using a semicolon to separate them won't work.

import subprocess subprocess.call(["sqlite3", "xxx.db",    ".mode tabs",    ".import file.tsv table_name"]) 
like image 170
polm23 Avatar answered Sep 20 '22 20:09

polm23


You can load new collating sequences and functions using load_extension() built-in SQLite function or .load command in command line shell for SQLite. Obviously, extensions shold be written in C.

And you can not call dot-commands from python, because dot-commands are specific to the command line shell tool.

like image 45
newtover Avatar answered Sep 21 '22 20:09

newtover