The db object

To connect to a database, just create a db object with the database name or connection url like so:

import databaseci 

# connect by name...
db = databaseci.db('example')

# or the equivalent URL (not 3 slashes not 2)....
db = databaseci.db('postgresql:///example')

See below for more on connection URLs, particularly if you're having trouble connecting or unsure about how to connect to a non-local server.

Creating a database object doesn't connect to the database straight away, but only on demand - for instance when you run a query:

db = databaseci.db('example')
# hasn't connected yet

# connects on this line:
print(db.q('select 1 as value'))

# value
# -----
#     1

Transactions

One-off queries can be run straight from the database object, but you'll probably want to run more complex operations within a transaction, created with a context manager as follows:

with db.transaction() as t:
    t.q('select 1 as value')

Connection URLs

URLs specify a protocol, connection information and a path.

For instance, consider a typical web URL:

https://example.com/model-trains

This effectively says: "Using the HTTPS protocol, connect to the server at example.com, and download the content at /model-trains.

Likewise, a database connection can be expressed as a protocol:

postgresql://database-server.example.com/example

This says: "Using the postgresql connection protocol, connect to the server at database-server.example.com and then connect to the example database on that server".

When connecting locally, we can set the server to localhost:

postgresql://localhost/trainsdb

Or leave it out entirely, making sure to keep the 3 slashes:

postgresql:///trainsdb

db( also accepts a name only as a connection string:

db('example')

Leaving the name entirely blank will try to connect to the local database matching the name of the current user.

Including credentials and other parameters

Credentials and other connection can be included in a connection string as per the following syntax:

postgresql://username:[email protected]:port/path?option1=x