I have this SQLite table:
create table mytable (
aid INTEGER NOT NULL PRIMARY KEY,
bid INTEGER NOT NULL,
image BLOB
);
And I want to insert a binary file into the image field in this table. Is it possible to do it from the sqlite3 command line interface? If so, how? I'm using Ubuntu.
Thank you!
The sqlite3 command line interface adds the following two “application-defined” functions:
readfile
which typically is used as: INSERT INTO table(blob) VALUES (readfile('myimage.jpg'))
writefile
which writes a file with the contents of a database blob and returns the count of bytes written.
You may use a syntax like :
echo "insert into mytable values(1,1, \"`cat image`\")" | sqlite3 yourDb
i'm not sure for the " around blob's value. Note the backquotes around cat command, means the cat command will be executed before the echo.
[EDIT]
Blob are stored as hexa digit with "X" prefix. You can use "hexdump" unix command to produce the hexa string, but it would be better to write a command line tool that read image and do the insert.
More details on this post : http://comments.gmane.org/gmane.comp.db.sqlite.general/64149
Related
"i am developing a mobile application with Ionic for a book that has a lot of content, grouping in
several parts, subpart, title and chapter. I chose to use SQLite, and I'm looking for a way to
load all its contents into my SQLite database and if anyone has an idea or suggestion to help me
do things well I'll be delighted."
There are several ways to import a text file, e.g. as a BLOB, on a line-to-row basis, using sqlite's "archive" mode, and so on.
If you want the entire file as a single TEXT cell in a table, then (subject to the limitation described below) you can use .import by carefully selecting values for the separators.
Multibyte separators are not supported when importing, but control characters such as Control-A and Control-B can be used.
So you could proceed like so:
CREATE TABLE text("text" text)';
.separator ^A ^B
.import text.txt text
where ^A should be replaced by a literal control-A, and similarly for ^B.
Limitation
The maximum number of bytes in a string or BLOB in SQLite is defined by the preprocessor macro SQLITE_MAX_LENGTH. The default value of this macro is 1 billion (1 thousand million or 1,000,000,000).
The following illustrates how to use the python sqlite3 module to import a (UTF-8) text file:
import sqlite3
def create_table():
conn.execute("""CREATE TABLE IF NOT EXISTS mytext( mytext TEXT );""")
def insert_file(filename):
sql = "INSERT INTO mytext(mytext) VALUES(?)"
cursor.execute(sql, (open(filename, "r").read(),))
conn.commit()
db_file_name = 'text-file.db'
conn = sqlite3.connect(db_file_name)
cursor = conn.cursor()
create_table()
insert_file("text.txt")
conn.close()
(Tested with python3.)
Here's what I am trying to do:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute(CREATE table Movies(index integer, mvnm text, year integer, genere text))
SyntaxError: invalid syntax
It highlights table in red color.
There are few problems:
The SQL should be provided in quotes because the execute() method accepts a
string argument.
index is a reserved keyword in SQL, so you cannot use
that as the name of your column.
If you want to run this script
repeatedly, you should add IF NOT EXISTS clause. Otherwise
consequent runs will fail due to "table already exists"
So, after these changes the statement looks like below:
c.execute("CREATE table IF NOT EXISTS Movies(myindex integer, mvnm text, year integer, genere text)")
You can then verify the table creation by logging in to sqllite:
$> ~ $ sqlite3 example.db
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> .tables
Movies
I can do it using the GUI (not that hard) but I really would like do to it by sqlite command lines. I've googled it and have tried everything, however nothing seems to work. Please give me a hint on this! This is the last thing I've tried:
CREATE TABLE 'teste3' (
'Id' integer,
'Idade' integer,
'Sexo' text,
'Peso' integer
);
.separator ',';
.mode csv;
.import 'C:\Users\xxxx\Documents\Monografia\base_teste.csv' teste3
What I intended to do was to create a table ('teste3',done) and them "fill it" by importing a given .csv file. Instead, I keep getting this error message: "near ".": syntax error:". Then I tried to cut off the "." before separator, for example, but I got another error: "near "separator": syntax error:". I really don't know what to do. Thanks!
Dot commands like .mode and .import are not SQL statements; they are implemented by the sqlite3.exe command-line shell (which can be downloaded from the offical SQLite site).
The DB Browser for SQLite is an entirely independent tool. It does not implement these dot commands; you have to use the GUI instead.
I have a SQLITE3 database wherein I have stored various columns. One column (cmd) in particular contains the full command line and associated parameters. Is there a way to extract just the first word in this column (just before the first space)? I am not interested in seeing the various parameters used, but do want to see the command issued.
Here's an example:
select cmd from log2 limit 3;
user-sync //depot/PATH/interface.h
user-info
user-changes -s submitted //depot/PATH/build/...#2011/12/06:18:31:10,#2012/01/18:00:05:55
From the result above, I'd like to use an inline SQL function (if available in SQLITE3) to parse on the first instance of space, and perhaps use a left function call (I know this is not available in SQLITE3) to return just the "user-sync" string. Same for "user-info" and "user-changes".
Any ideas?
Thanks.
My soluion:
sqlite> CREATE TABLE command (cmd TEXT);
sqlite> INSERT INTO command (cmd) VALUES ('ls'),('cd ~'),(' mpv movie.mkv ');
sqlite> SELECT substr(trim(cmd),1,instr(trim(cmd)||' ',' ')-1) FROM command;
ls
cd
mpv
Pros:
it's not that a dirty hack
it only uses core functions
"Finds the first occurrence" function is one of the SQLite3 Core Functions (http://www.sqlite.org/lang_corefunc.html).
Of course, it is much better to use instr(X,Y).
So you can write:
SELECT substr(cmd,1,instr(cmd,' ')-1) FROM log2
As the position of your first space character is unknown, I don't think there is a corefunction in SQLite that will help.
I think you'll have to create one http://www.sqlite.org/c3ref/create_function.html
Here's a hack
sqlite> create table test (a);
sqlite> insert into test values ("This is a test.");
sqlite> select * from test;
This is a test.
sqlite> select rtrim(substr(replace(a,' ','----------------------------------------------------------------------------------------'),1,80),'-') from test;
This
It works as long as your longest command is less than 80 characters (and you include 80 '-' characters in the substitution string -- I didn't count them!). If your commands can contain '-' just use a different character that is not allowed in the commands.
I don't believe that's something you'll be able to do within the SQL itself. SQLite's support for string handling functions is not as extensive as other RDBMSs (some of which would let you do a SUBSTR with a Reg Exp).
My suggestion is either to write your own SQL function as suggested by #Jon or just do it as a post-processing step in your app code.
I am using a sqlite database.
I want to excute sqlite from dos command line and insert fields into the tables by passing them as parameters from command line.
C:\run.bat name surname
want to create the run.bat file ...
sqlite > INSERT into tab(col1, col2) Values (%1,%2);
I guess you're looking for something like this:
sqlite3 DATABASENAME 'insert into dbo.TABLE values('%1', '%2')'
You'll need the command line program sqlite3.exe. Then you can put into your batch file:
sqlite3 dbname "INSERT INTO TableName (ColName1, ColName2) VALUES (%1, %2);"
Also note that you will have to be aware of the datatypes of the columns and, if the VALUES for those datatypes require quoting, you'll need to add the quotes into the command line (and handle embedded quotes in the values, if that's a possible occurence).