Posts tagged ‘SQLite’

Fehlerhafte SQLite Updates abfangen

Bei einem kleinen Projekt, an dem ich arbeite, fiel mir auf, dass fehlerhafte — d.h. syntaktisch richtige, aber inhaltlich falsche — SQLite Updates im Nirvana verschwinden. Danke Google und Stackexchange war die Lösung wie folgt: fehlerhafte SQL-Updates erzeugen keine Exception, hier muss man nach dem Update den rowcount prüfen, um die Anzahl der aktualisierten Zeilen zu checken. Das folgende Programm illustriert das ganze:

import sqlite3
 
conn = sqlite3.connect(':memory:')
conn.execute('create table if not exists mytable(id INTEGER PRIMARY KEY \
             AUTOINCREMENT, status TEXT, prio TEXT)')
 
today = '2020-08-06'
cursor = conn.cursor()
task = "Foobar"
 
cursor.execute('insert into mytable(status, prio) values (?, ?)',
               [task, today])
conn.commit()
 
my_id = 1 # For my_id = 1 it works, for any other number rowcount is 0
prio = 'A'
cursor = conn.cursor()
cursor.execute('UPDATE mytable SET prio = ? WHERE id = ?', [prio, my_id])
conn.commit()
print(cursor.rowcount)
 
try:
    cursor = conn.cursor()
    cursor.execute('select * from mytable')
    results = cursor.fetchall()
    for entry in results:
        print(entry)
except Exception as err:
    print('Listing failed: %s\nError: %s' % str(err))
 
finally:
    cursor.close()

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Dynamische Reports mit R

Vor kurzem hat mich jemand gefragt, wie man denn mit R Reports dynamisch gestalten könne. Ausgehend von Erfahrungen, die ich damals beim automatisierten Textsatz eines Konferenzprogramms sammeln konnte, war die Lösung nicht schwer.

Ausgangspunkt ist eine CSV Datei, die über das RSQLite Paket in eine in-memory Datenbank geladen wird. Auf des Basis dieser Datenbank werden dann ein paar SQL-Statements aufgebaut, die dann beliebig ausgewertet werden können.

# read excel table from csv to dataframe
df = read.table("g:/datasource.csv",sep=";",header=TRUE)
 
# set up plot window
par(mfrow = c(3,2))
 
# load SQlite library
library("RSQLite")
 
# create fresh database in memory
db <- dbConnect(SQLite(),dbname=".memory.")
 
# write dataframe to database
dbWriteTable(db, "kpi", df) 
 
# list all tables in db 
dbListTables(db)
 
# get a vector of all departments
departments = dbGetQuery(db, "Select distinct(department) from kpi")
 
 
for(i in 1:nrow(departments)){
	print(paste("Department",departments[i,1],sep=" "))
	statement = paste("Select distinct(manager) from kpi where department='",departments[i,1],"'",sep="")
	# print(statement)
	manager = dbGetQuery(db, statement)
 
	for(j in 1:nrow(manager)){
		print(paste("Manager",manager[j,1],sep=" "))
		statement = paste("Select distinct(employee) from kpi where department='",departments[i,1],"'"," and manager='",manager[j,1],"'",sep="")
		# print(statement)
		employee = dbGetQuery(db, statement)
 
		for(k in 1:nrow(employee)){
			print(paste("Employee",employee[k,1],sep=" "))
			statement = paste("Select kpi1,kpi2,kpi3 from kpi where department='",departments[i,1],"'"," and manager='",manager[j,1],"' and employee='",employee[k,1],"'",sep="")
			# print(statement)
			fulldata_employee = dbGetQuery(db, statement)
			# print(fulldata_employee)
			x <- c(1,2,3)
			plot(x,fulldata_employee,type="l",main=paste(departments[i,1],manager[j,1],employee[k,1],sep=" "))
		}
	}
}
 
dbDisconnect(db)

R

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website