1.4.3 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(adapter="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( adapter,[database,][user,][password,][host,][port,][socket,][**params])

Constructor for creating a connection to a database. Returns a Connection object. Not all databases will use all the parameters, but databases should use the parameters specified and not abbreviated versions. Any more complex parameters are passed directly to the underlying driver's connect() method.

adapter
The type of database to connect to. Can currently be 'MySQL', 'PySQLite' or 'web.database ' but it is hoped that most database drivers will eventually be supported.
database
The database name to connect to.
user
The username to connect with.
password
The password to use.
prepend
A string to be transparantly used in front of all database tables.
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.
**params
Any other parameters to be passed to the driver

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(
    adapter="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(
    adapter="mysql",
    database="MyDatabase",
    host="mysql.example.com",
    port="3336",
    user="username",
    password="password",
)

Connect to the web.database database in the directory C:/TestDirectory

connection = web.database.connect(
    adapter="SnakeSQL",
    database="C:/TestDirectory",
)

Note: Windows users may find it easier to use forward slahes in paths to avoid having to quote backslashes. Both work equally well.