Shell脚本SQLite

Cod*_*ker 7 sqlite shell

如何编写显示SQLite结果的shell脚本?我编写了一个脚本,为SQLite数据库添加了一个条目.现在我想在添加该条目后显示结果.这是我的脚本:

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

在此之后,我希望脚本回显/吐出语句的输出:

select sum(Average) from (select * from myTable where Category = 'category1');
select sum(Average) from (select * from myTable where Category = 'category2');
Run Code Online (Sandbox Code Playgroud)

格式应该是这样的:

Category1 total = <output of first statement>
Category2 total = <output of second statement>
Run Code Online (Sandbox Code Playgroud)

而已.我对SQL很陌生,而且shell脚本不是很好.我也在寻找解释这类问题的好教程.

she*_*ter 12

解决此问题的一种常见方法是使用名为here文档的shell功能,试试这个:

 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
Run Code Online (Sandbox Code Playgroud)

请注意,EOS可以是您喜欢的任何字符串(我认为是EndOfScript),但它必须在最后一行文本中单独使用,没有尾随空格.

由于我不使用sqlite3,您可能需要一些语句来关闭我不知道的批处理.此外,我不确定'$ 1'的东西是否会起作用,如果sqlite3是宽容的,请尝试"$ 1"等.此外,您可能需要在"CategoryN total = "字符串后面添加逗号.

请注意,此解决方案允许您根据需要创建sql DML语句.对于经常发生的事情以及它在大型表格上的范围,如果您对我们的系统有权限,您可能需要将DML存储到存储过程并调用它.

我希望这有帮助.

(如果这不起作用,请编辑您的帖子以指示您正在使用的shell,OS/Linux Ver以及您获得的最小版本的错误消息).


Tha*_*nga 5

如果需要将sqlite SELECT结果分配给shell变量,则可以执行此操作。

r=$(sqlite3 your_db_path.db "select something from some_table where condition")
Run Code Online (Sandbox Code Playgroud)

$r 将是您的变量。

单行也可以获取。您可以做一些工作将其拆分为一个数组,可能正在使用IFS

另外,请记住#!/bin/bash在每个shell脚本的顶部都使用约定。它将解决许多不需要的问题。有时旧的#!/bin/sh惯例会带来麻烦。:)。