home

Dokumentation Databases

 

Module import: from sqlite3 import *

Access to a SQLite database (almost 100 % compatible with the sqlite3 module from Python 2.x, 3.x).

Global:
Function Action
connect(database)


connects to a SQLite database file with given filenames, and returns a Connection object. If the database file does not exist, it is created. The database is opened for exclusive access until it is closed with close ()

connect(database, True) same, but opens the database in auto-commit mode. All database operations become effective immediately
getDbInfo(database) returns a dictionary with all table names and their attributes

class Connection:
Method Action
cursor()

creates and returns a database cursor

execute(sql) executes the SQL command (does not take effect in the database until commit()) and returns the cursor used
commit() one or more previously issued SQL commands are written into the database
close() terminates the connection to the database. Commands that are not completed with commit() are lost. If the program is aborted by an exception, the connection remains open and TigerJython must be restarted to establish a new connection
showTables() returns a list of table names
describeTable(table) returns the information about the table structure as an SQL Create command


class Cursor:
Method Action
execute(sql)

executes the SQL command (does not become effective in the database until commit()). For SELECT, a result set is generated, which can be traversed with the cursor

fetchone() returns the record pointed to by the cusor, and moves the cursor to the next record. If no result set was created or the cursor is outside the result set, None is returned
fetchmany(n) returns a list of the n next records (starting from the record pointed to by the cusor) and moves the cursor forward by n. If no result set was created, n <1, or if the cursor is outside the result set, an empty list is returned. If there are not enough records, the rest of the records are returned
fetchall() returns a list of all records (starting from the record pointed to by the cursor). If no result set was created, an empty list is returned
getColumnNames() returns a list with the field names of the SELECT command
getColumnName(n) returns the field name of the nth field of the SELECT command (n = 1st. number of fields)
getColumnCount() returns the number of fields in the SELECT command
getMetaData() returns a MetaData object (JDBC4ResultSet)
getBytes(filename) returns a byte array (type: array.array) of the binary data from given file (absolute or relative path with respect to the current program location)
updateBlob(table, where, attribute, buffer) updates the BLOB field with given attribute in all records of given table that fullfil the where condition.
buffer contains the binary data (normally returned from the global function getBytes(), type array.array). Example: update(tbl, "id = 1", "flags", getBytes("swissflag.gif"))

Note: If the Connection object con is used in a with con: block, con.commit() and con.close() are automatically called at the end of the block. The database is also closed securely with exceptions. Example:

from sqlite3 import *
with connect("test.db") as con:
    con.execute("DELETE FROM people")


Module import: from dbapi import *

Access to various databases: PostgreSQL, SQLite, MySQL, Derby (via JDBC drivers).

Function Action
connect(sqlite:dbname) connects to a SQLite database and returns a Connection object
connect(derby:dbname) connects to an embedded Derby database and returns a Connection object
connect(derbyserver:serverURL, dbname, username, password)

connects to a Derby server database and returns a Connection object

connect(mysql:serverURL, dbname, username, password) connects to a MySQL database and returns a Connection object
connect(postgre:serverURL, dbname, username, password) connects to a PostgreSQL database and returns a Connection object

The JDBC drivers can be downloaded from here. They must reside in the subdirectory Lib of the tigerjython2.jar home directory.
The database API largely corresponds to the Python Database API Specification v2.0.

 

Module import: from prettytable import *

Formated output of table data (cursor is a database cursor from SQLite)

Function Action
printTable(cursor)

executes a cursor.fetchall() and displays the result in the console left-aligned (a second call results in an empty result set)

strTable(cursor)

same, but returns the formatted result as a string
printTable(cursor, align = "x") as above, but all columns for x = "l" left-aligned, "c" centered, "r" right-aligned (same for strTable())
printTable(cursor, align = ["x", "x", ...]) as above, but columns are aligned one-by-one for x = "l", "c", "r" (same for strTable())
printTable(cursor, align = ["x", "x", ...], sortby = fieldname) as above, but the output is alphabetically sorted according to the given database field (column) (the same for strTable())
showTable(cursor, params) same as printTable(), but the table is displayed in its own window

The module can also be used for tabular formatted output without any database connection. See the tutorial hier.


Module import: from dbtable import *

Abstraction of database tables without SQL

Module import: from dbtable import *

Abstraction of database tables without SQL

Class DbTable

Function/Method Action
tbl = DbTable(fieldname1, fieldname2,...)

creates a table object with any number of field names (as string). The names may be packed in a tuple

tbl = DbTable(anotherTable)

creates a (deep) clone of the table object

tbl = DbTable()

creates an empty table that can be used for restore(), restoreFromTJ() or importFromCSV()

tbl.insert(value1, value2,...)

inserts a row with given values into the table. The values can be packed in a tuple. Allowed data types: str, int, float, BLOB (binary). All fields must be given. The database field types are determined from the first row entered Binary field values are byte arrays (return value of getBytes(filename))

tbl.insertMany(liste) inserts several rows packed in the given list (or tuple) (i.e. the return value of select() ). The database field types are determined from the first row entered (int, float or str)
for row in tbl:
     do_something_ with row.fieldname
Iterates through all rows and uses the field values
tbl.select(fieldname1, fieldname2, ..., pattern)

returns a tuple containing the given fields. If sort() was called before, the rows are returned in the requested order. patter is a sequence of equality conditions attribute = value. If an attribute is not specified, all values are accepted. Example: select("name", "firstname", "age", name = "Smith", firstname = "John" returns fields "name", "firstname" and "age" of every "Smith John". The values has the data types str, int or float

tbl.sort(fieldname)

defines a field name (string) as sorting attribute. Table views and select() are then returned in the given ascending order. If no sort() is called, the order of the views and select() is undefined, but corresponds normally to the order the table rows are inserted

tbl.sort(fieldname, False) same, but descending order
tbl.getAttributes() returns a tuple with all field names (attributes)
tbl.view() shows the table in the console using a tabular format (order given by sort())
tbl.view(fieldname1, fieldname2, ..., pattern) same, but shows only fields with given name that fulfill the equality conditions (like select())
tbl.getView() same, but returns the view in a string
tbl.getView(fieldname1, fieldname2, ..., pattern) same, but returns only fields with given name that fulfill the equality conditions (like select())
print tbl same as tbl.view()
len(tbl) returns the number of table rows
tbl.delete(pattern)

erases all rows that fullfil the equality conditions in pattern (like in select()). Example: delete(name = "Smith", firstname = "John") deletes all rows with "Smith John")

tbl.update(pattern)(fieldname1 = value1, fieldname2 = value2,...)

replaces the values of certain fields. Two parameter parenthesis are used. In the first parameter parenthesis, pattern selects the rows to modify (like with select()); the second parenthesis is used to set the new values. (Example: update(name = "Smith", firstname = "John")(city = "Paris") sets the city of all "Smith John" to "Paris"). If the first paranthesis is empty, all rows are modified

tbl.join(otherTable, left, right)

returns a table join of the current table with otherTable, where attribute values left and right must the same. The attribute fields are not part of the returned table. (Example. person.join(sport, person.id = sport.id))

tbl.join(otherTable, left, right, True)

same, but the attribute fields are part of the returned table (they must have different names)

tbl.join(otherTable) same, but all rows of both tables are combined (cross product)
tbl.save(databaseName, tableName)

stores the table data in an external SQLite database with given SQLite table name. If the database does not exist, it is created. If the same SQLite table is already part of the database, it is deleted. The field names (attributes) and field types are maintained. If tableName is omitted, the variable name is used as SQLite table name

tbl.restore(databaseName, tableName)

restores the table data from the SQLite database created with saveTable(). tbl should be an empty table created with DbTable(). If an non-empty table is used, all table data are erased. The field names and data types are maintained. If tableName is omitted, the variable name is used as SQLite table name

tbl.restoreFromTJ(databaseName, tableName) same, but the SQLite database is supposed to be part of the TigerJython distribution (tigerjython2.jar) and first copied into the current directory
tbl.importFromCSV(filename, delimiter)

imports the content of the CSV formatted file (text file). The fields must be separated by the given delimiter. Each line must contain the same number of fields. The data type is determined form the first line (int, float, str)

tbl.exportToCSV(filename, delimiter, fieldname1, fieldname2, ..., pattern)

exports the table data in a CSV formatted file (text file), where the fields are separated by the given delimiter. Only fields with given field names are exported. pattern is sequence of equality conditions attribute = value (like in select()). If no fieldnames or pattern is specified, the complete table is exported

getBytes(filename) returns a byte array (type: array.array) of the binary data from given file (absolute or relative path with respect to the tigerjython2.jar home directory)
storeBytes(buffer, filename) writes a byte array (type array.array) into file (replaces an existing file)
showDbInfo(database) displays all table names and their attributes of the given database
showDbInfoTJ(database) displays all table names and their attributes of the given database that is part of the TigerJython distribution

 

 

home