SQLite Shell Scripting

How to write a shell script that displays SQLite results? I wrote a script that adds an entry to the SQLite database. Now I want to display the results after adding this entry. Here is my script:

echo 'insert into myTable (Date, Details, Category, Average) values (datetime('\''now'\'','\''localtime'\''), '\'''$1''\'', '\'''$2''\'', '$3');'|sqlite3 /Users/user/Documents/Test/dbName.db

After that, I want the script to echo / spit out the output of the statements:

select sum(Average) from (select * from myTable where Category = 'category1');
select sum(Average) from (select * from myTable where Category = 'category2');

The format should look like this:

Category1 total = <output of first statement>
Category2 total = <output of second statement>

Here it is. I am new to SQL but not so good at shell scripts. I am also looking for good tutorials explaining such issues.

+5
source share
2 answers

One common way to solve this problem is to use a wrapper function called a document here, try the following:

 sqlite3 /Users/user/Documents/Test/dbName.dba <<EOS
     insert into myTable (Date, Details, Category, Average) 
               values(datetime('now','localtime'), '$1', '$2', '$3');

     select "Category1 total = " sum(Average) from (
          select * from myTable where Category = 'category1'
     );

     select "Category2 total = " sum(Average) from (
         select * from myTable where Category = 'category2'
     );

 EOS

, EOS , ( , EndOfScript), .

sqlite3, - , , . , , "1 " , sqlite3 , "$ 1" .. , "CategoryN total = ".

, SQL- sql, , . , , , , , DML .

, .

( , , , , OS/Linux Ver , ).

+9

SELECT SELECT , .

r=$(sqlite3 your_db_path.db "select something from some_table where condition")

$r .

. , , IFS

, #!/bin/bash script. . #!/bin/sh .:.)

+3

All Articles