SQLite

Mureakuha

Loikkaa: valikkoon, hakuun

SQLite on pienimuotoinen SQL-tietokantajärjestelmä, jota käytetään monelle kielelle saatavilla olevien kirjastofunktioiden kautta. Se ei siis ole palvelinpohjainen jatkuvasti käynnissä oleva tietokantamoottori, vaan yhden tiedoston käsittävää tietokantaa operoidaan suoraan ajettavasta ohjelmasta käsin.

SQLite soveltuu parhaiten tilanteisiin, joissa tekstitiedoston käyttö datan tallentamiseen ei riitä, mutta oman SQL-palvelimen asentaminen olisi liioittelua.

Sovellusesimerkki (Python)

Siirretään dataa tekstitiedostosta SQLite-kantaan. Kanta on jo valmiiksi luotu (esim. konsolin avulla) ja se sisältää Acronym-taulun.

import sqlite
 
cx = sqlite.connect("chbot.db")
cu = cx.cursor()
f = file('acronyms.txt', 'r')
n = 0
 
for row in f:
    acr, text = row.strip().split(' ', 1)
    cu.execute("INSERT INTO 'Acronym' VALUES ('%s', '%s')" % (acr, text))
    n += 1
 
cu.close()
cx.commit()
cx.close()
print 'Added %d rows' % n

Käyttöesimerkki (TCL)

Kirjoittaa sntop-ohjelman varoitukset SQLite-kantaan.

 #!/usr/bin/tclsh
 # $Id: alarm.tcl 9 2005-07-11 20:58:26Z raspi $
 # Alarm for sntop
 
 set mondb "netmon-sqlite.db";
 
 load /usr/lib/sqlite3/libtclsqlite3.so.0 Sqlite3;
 
 proc puts2 {s} {
   # debug..
   puts $s;
 }
 
 proc IPtoHex {IP} {
   binary scan [binary format c4 [split $IP .]] H8 Hex
   return $Hex
 }
 
 proc ipToInt {ip} {
   set ipre {^\d+\.\d+\.\d+\.\d+$}
   if {[regexp -nocase $ipre $ip]} {
     set hex [IPtoHex $ip];
     return [format "%#u" [expr "0x$hex"]]
   } else {
     return 0;
   }
 }
 
 proc putError {msg msg2 ec q} {
   puts $msg
   puts "Errorcode: $ec";
   puts $msg2
   puts "Query: $q"
 } 
 
 if {![file exists $mondb]} {
   set db_exists 0;
   set q "CREATE TABLE alarm (id INTEGER PRIMARY KEY, status INTEGER, time INTEGER, ip INTEGER);";
 } else {
   set db_exists 1;
 }
 
 sqlite3 db $mondb;
 
 if {!$db_exists} {
   puts2 "Creating database '$mondb'..";
   if {[catch {set ret [db onecolumn $q];} msg] == 0} {
     puts2 "Database '$mondb' created succesfully";
   } else {
     putError "Error occured during database '$mondb' creation!" $msg [db errorcode] $q; 
     db close;
     file delete -- $mondb;
     exit 1;
   }
 }
 
 if {$argc <= 1} {
   puts "sntop runs this."; 
   exit 1;
 }
 
 if {[lindex $argv 2] == "DOWN"} {
   set bStatus 0;
 } else {
   set bStatus 1;
 }
 
 set iIp [ipToInt [lindex $argv 1]];
 set sComment [lindex $argv 0];
 set iTime [clock seconds];
 set t [clock format $iTime -format "%H:%M:%S %d.%m.%Y"];
 
 set q "INSERT INTO alarm (status,time,ip) VALUES ($bStatus, $iTime, $iIp);"
 
 if {[catch {set ret [db onecolumn $q];} msg] == 0} {
   puts2 "$t: Row inserted successfully.";
   #puts2 "Query: '$q'"
 } else {
   putError "$t: Error occured during database inserting!" $msg [db errorcode] $q;
 }
 
 db close;
 exit 0;

Lisätietoa verkossa

Henkilökohtaiset työkalut