Morpe
Morpe

Reputation: 1

SQLite executing .import cmd from Java

I want to use the sqlite3 shell command .import to load a tab separated file into my database.

Executing the command from shell is no problem!

Writing a shell script including the command and running it from Java is no problem!

#! /bin/bash
# Script for loading a specific file ($1) into a SQLite DBS table ($2)
{
    sqlite3 database.db -cmd ".mode tab" -cmd ".import $1 $2" -cmd ".quit" &
} 2> /dev/null
exit 0

But how do I execute the command directly from Java? Here is what I've tried: But somehow nothing is loaded into the database

String[] cmd={"sqlite3","database.db -cmd \".mode tab\" -cmd \".import\" "+file.getPath()+" "+table+" -cmd \".quit\""};
Runtime.getRuntime().exec(cmd);

Upvotes: 0

Views: 1272

Answers (2)

Tim Kolecke
Tim Kolecke

Reputation: 11

Try executing the commands grouped by double-quotes.

sqlite3 database.db ".mode tab" ".import $1 $2"

Upvotes: 1

hflzh
hflzh

Reputation: 644

I do not find the "-cmd" option from the SQLite3 shell docs: http://www.sqlite.org/cli.html. I tried the shell script you provided:

sqlite3 database.db -cmd ".mode tab" -cmd ".import data.in Test" -cmd ".quit"

The error gets reported:

./sqlite3: Error: too many options: ".mode tab"
Use -help for a list of options.

To execute multiple commands on a SQLite shell, I would write all the commands in one file and use the ".read" command. For example, write the commands in cmd.list

.mode tabs
.import data.in Test
.quit

Then run the SQLite shell command:

sqlite3 database.db ".read cmd.list"

Java code:

String[] cmd = {"sqlite3", "database.db", ".read cmd.list"};
Runtime.getRuntime().exec(cmd);

Upvotes: 0

Related Questions