1.4.2 Connecting to a Database

Connecting to a database is really very easy. The code below will connect to a MySQL database named 'test'.

import web, web.database
connection = web.database.connect("mysql", database="test")

Below is a description of the full range of parameters the connect() function can take (Obviously not all of the database support all of the parameters):

connect( type,[database,][user,][password,][host,][port,][socket])
type
The type of database to conncet to. Can currently be 'mysql', 'gadfly' or 'odbc'.
database
The database name to connect to.
user
The username to connect with.
password
The password to use.
host
The host to connect to if the database is running on a remote server.
port
The port to connect to if the database is running on a remote server.
socket
The socket to connect to if the database is running locally and requires a socket.
dir
The directory containing the database.
startup
Whether to connect to Gadfly in the special startup mode for creating tables. Can be True or False. Left blank is the same as startup=False.

Here are some examples:

Connect to the unpassworded MySQL database MyDatabase on a local server connected through a socket /tmp/mysqld.sock. Another common socket file used is /tmp/mysql.sock.

connection = web.database.connect(
    type="mysql", 
    database="MyDatabase",
    socket="/tmp/mysqld.sock"
)

Connect to a the database MyDatabase as username with password password. The MySQL server is runing remotely at mysql.example.com on port 3336:

connection = web.database.connect(
    type="mysql",
    database="MyDatabase",
    host="mysql.example.com",
    port="3336",
    user="username",
    password="password"
)

Connect to the Gadfly database TestDB in the directory C:/TestDirectory

connection = web.database.connect(
    type="gadfly",
    database="TestDB",
    dir=r"C:/TestDirectory"
)

Connect to the database TestODBCDatabase through an ODBC driver. The database could be an MS Access database on Windows for example.

connection = web.database.connect(
    type="odbc",
    database="TestODBCDatabase"
)

See About this document... for information on suggesting changes.