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):
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.
'MySQL'
, 'PySQLite'
or 'web.database '
but it is hoped that most database drivers will eventually be supported.
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.