Step 3: Data Access Operations

To perform operations on database objects the Python application must first establish a connection to the database. After calling the exdb.open_database() method, the application calls the Database method connect() to create a database connection handle:

 
    >>> con = db.connect()
    >>>
     

The variable con is the connection handle. When finished, it is necessary to close the database connection:

 
    >>> con.close()
 

Inserting Database Objects

All database access in eXtremeDB, with any of its APIs (including Python), must be within the scope of a transaction. To start a transaction on a connection:

 
    >>>con.startTransaction()
    >>>
     

To create an object (i.e. insert a record into the database) use Connection method new() which takes a class name as argument. It returns a Python object which corresponds to the one created in the database. The type for the python object is dynamically defined from the schema when the database is created. For example:

 
    >>> o = con.new(“myclass”)
    >>>
     

The variable ‘o’ is a python object of type “myclass” (as defined in the schema). We can now view its fields by typing the variable name:

 
    >>> o
    <eXtremeDB object:myclass>.{'i4':0L}
     

We can assign a field’s value, for example:

 
    >>> o.i4=10
    >>> o
    <eXtremeDB object:myclass>.{'i4':10}
     

Finally, commit the transaction to complete the operation:

 
    >>> con.commit()
    >>>
     

Retrieving and Updating Database Objects

A Cursor is used to retrieve database objects. Then the Cursor method find() can be used to locate an object by a unique index. The following code snippet performs a simple index search to locate a Record object by unique key id; then updates the string field str and commits the transaction:

 
    con.startTransaction(exdb.Transaction.MCO_READ_WRITE)
    cursor = con.cursor()
    rec = cursor.find("Record", "by_i4", 2)
    rec.str = "Updated string"
    cursor.close() #release cursor
     con.commit() # commit changes
     

A Cursor is also used to retrieve and scroll through a set of database objects satisfying an index search condition. The following code snippet retrieves all Record objects having values greater than or equal to 2 for field i4 using the Cursor method search(); then scrolls through the result set:

 
    con.startTransaction(exdb.Transaction.MCO_READ_ONLY)
    cursor = con.cursor()
    ret = cursor.search("Record", "by_i4", exdb.Operation.GreaterOrEquals, 2)
    if ret:
        for rec in cursor:
            print "Object found: i4=%s,str=%s" % (rec.i4, rec.str)
             
    else::
        print "Object not found"
     
    cursor.close()
    con.commit()
     

SDK sample samples/python/operations illustrates how to use the Connection and Cursor classes to perform basic database CRUD operations. Please build and run the sample application and examine the source code.