sqlite mit python

Zur Datenspeicherung in lokalen Programmen bietet sich die Datei-basierte Datenbank sqlite ideal an!

Die folgende Klasse stellt dabei die Grundlegenden Funktionen zum Umgang mit einer sqlite Datenbank zur Verfügung:

import os
import sqlite3
 
###############################################################################
# modifies the delivery database                                              #
# lists, adds and removes projects or recipients                              #
###############################################################################
class sqliteDB:
 
  #############################################################################
  # Creates a new sqlite database                                             #
  #############################################################################
  def create(self, dbfile):
    if not os.path.isfile(dbfile):
      self.sqlquery(dbfile, "CREATE TABLE 'table1' ('TID' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'TOtherTableID' INTEGER NOT NULL, 'TName' TEXT NOT NULL, 'TDescription' TEXT)")
      return dbfile
    else:
      return 1
 
 
  ###############################################################################
  # queries the database and returns a dictionary of rows                       #
  #                                                                             #
  # takes:   string            = String of SQL-Code                             #
  # returns: dict              = dict of rows                                   #
  ###############################################################################
  def sqlquery(self, dbfile, sql):
    try:
      con = sqlite3.connect(dbfile)
      con.row_factory = sqlite3.Row
      cur = con.cursor()
      cur.execute(sql)
      con.commit()
 
      rows = cur.fetchall()
      con.close()
 
    except sqlite3.Error, e:
      msg = "Error %d: %s" % (e.args[0], e.args[1])
      print msg
 
    return rows

Und so wird die sqliteDB-Klasse Benutzt:

# Define database file
myDBfile = "sqlite.db"
 
# Create a new database
myDB = sqliteDB().create(myDBfile)
if myDB == myDBfile:
  print "Created database: '{myDB}'".format(myDB = myDB)
else:
  print "DB file already existent. If you want to create a NEW database, please delete the file:\n{filename}\n".format(filename = myDBfile)
 
# Insert data in database
sqliteDB().sqlquery(myDBfile, "INSERT INTO table1 (TOtherTableID, TName) VALUES (1, 'My first row')")
sqliteDB().sqlquery(myDBfile, "INSERT INTO table1 (TOtherTableID, TName) VALUES (2, 'My second row')")
 
# Select data from database
rows = sqliteDB().sqlquery(myDBfile, "SELECT TName FROM table1")
 
# Show data
for row in rows:
  print row['TName']
 
# Delete data
sqliteDB().sqlquery(myDBfile, "DELETE  FROM table1  WHERE TOtherTableID = 2")

Published by

Steven Varco

Steven ist ein Redhat RHCE- und Kubernetes CKA Zertifizierter Linux-Crack und ist seit über 20 Jahren sowohl beruflich wie auch privat auf Linux spezialisiert. In seinem Keller steht ein Server Rack mit diversen ESX und Linux Servern.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert