01
Mar
07

SQLite examples with Bash, Perl and Python

If you are looking for a lightweight database solution take a look on SQLite. I made some very simple examples with Perl, Python and Bash interfacing with sqlite. Just when I have finished I find out this article bellow that have also some examples in Perl and Python to start playing. Take a look!

http://www.linuxjournal.com/article/6650/

Well, all those samples do the same thing. First it creates a table “n” with columns “f” and “l”. Then it insert (“john”, “smith”) as an entry. And finally dumps everything it finds in table “n”.

The perl sample.

#!/usr/bin/perl -w
use DBI;
use strict;
my $db = DBI->connect("dbi:SQLite:test.db", "", "",
{RaiseError => 1, AutoCommit => 1});

$db->do("CREATE TABLE n (id INTEGER PRIMARY KEY, f TEXT, l TEXT)");
$db->do("INSERT INTO n VALUES (NULL, 'john', 'smith')");
my $all = $db->selectall_arrayref("SELECT * FROM n");

foreach my $row (@$all) {
my ($id, $first, $last) = @$row;
print "$id|$first|$lastn";
}

The python sample.

#!/usr/bin/python
from pysqlite2 import dbapi2 as sqlite

db = sqlite.connect('test.db')
cur = db.cursor()
cur.execute('CREATE TABLE n (id INTEGER PRIMARY KEY, f TEXT, l TEXT)')
db.commit()
cur.execute('INSERT INTO n (id, f, l) VALUES(NULL, "john", "smith")')
db.commit()
cur.execute('SELECT * FROM n')
print cur.fetchall()

The bash sample.

#!/bin/bash
sqlite3 test.db  "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"
sqlite3 test.db  "insert into n (f,l) values ('john','smith');"
sqlite3 test.db  "select * from n";

Got free time? Spend 5 min and write the same for ruby, tcl, php…
and post as a comment here! Thank you very much!


15 Responses to “SQLite examples with Bash, Perl and Python”


  1. 1 random vistor
    March 30, 2007 at 13:54

    query(‘CREATE TABLE n (id INTEGER PRIMARY KEY, f TEXT, l TEXT);’);
    $DB->query(“INSERT INTO n (f, l) VALUES (‘john’, ‘smith’);”);
    // Prepared query
    $q=$DB->query(‘SELECT * FROM n;’);
    print_r($q->fetch(PDO::FETCH_ASSOC));
    ?>

    # Bash again – check if a table exists
    DB=”test.db”

    function table_exists(){
    Q=”SELECT name FROM sqlite_master WHERE type=’table’ AND name=’$1′;”
    R=`sqlite3 $DB “$Q”`
    if [ “$R” = “$1” ]; then
    echo 1
    else
    echo 0
    fi
    }

    STATE=$( table_exists “n” )
    if [ “$STATE” -gt 0 ]; then
    sqlite3 $DB “CREATE TABLE n (id INTEGER PRIMARY KEY, f TEXT, l TEXT);”
    else
    echo “TABLE ALREADY EXISTS”
    fi

  2. 2 random vistor
    March 30, 2007 at 13:58

    Because WordPress destroyed the PHP example: http://pastebin.ca/416797

  3. 3 Fred
    July 31, 2009 at 12:24

    Hi,

    No example to add, sorry about that. However, I think I’ve found a very minor typo in your bash example.

    sqlite3 test.db “select * from n”;

    …should probably be…

    sqlite3 test.db “select * from n;”

  4. 4 darkwurm
    January 9, 2011 at 15:50

    You’ll note that the bash example is the least complex.

  5. 5 MagikK
    April 11, 2012 at 13:36

    print “$id|$first|$lastn”; <— little mistake with $lastn should be $last\n 😉

  6. 6 Robin Randall
    January 25, 2015 at 21:55

    fyi there is a typo – “bellow” should be “below” on home page. Your neighborhood QA

  7. November 9, 2015 at 04:16

    We’re a group of volunteers and opening a new scheme in our community.
    Your website provided us with useful info to work on.
    You’ve performed a formidable activity and our whole group will be thankful to you.

  8. February 19, 2016 at 04:00

    Wonderful article! We will be linking to this particularly great post on our
    website. Keep up the great writing.

  9. 9 Odranoel Gaisus
    April 27, 2016 at 11:38

    What about inserting values that contain spaces – this example will not work.

  10. 10 varro
    February 15, 2017 at 23:29

    The bash example could be improved by only invoking sqlit3 one, e.g,:

    #!/bin/sh
    sqlite3 test.db <<EOF
    create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);
    insert into n (f,l) values ('john','smith');
    select * from n;
    EOF

    Note in passing that unless bash is *really* required elsewhere in the script, it is better to use "#!/bin/sh" as a shebang, for portability.

  11. February 3, 2020 at 18:00

    Undeniably consider that which you stated. Your favorite reason appeared to be at the web the simplest factor to be aware of.
    I say to you, I certainly get annoyed at the same time as other folks think
    about issues that they plainly don’t recognise about. You managed to hit the nail upon the highest and
    outlined out the whole thing with no need side effect , other people could take a signal.

    Will likely be again to get more. Thank you


Leave a comment


Quotes

"Don't worry about what anybody else is going to do. The best way to predict the future is to invent it. Really smart people with reasonable funding can do just about anything that doesn't violate too many of Newton's Laws!" -- Alan Kay in 1971

My Delicious

RSS My Shared RSS

  • An error has occurred; the feed is probably down. Try again later.

Blog Stats

  • 80,646 hits

Design a site like this with WordPress.com
Get started