The Connection class is part of the gb.db component and represents a connection to a database. An instance can be created using source code.
Note: The classes DB (also part of the gb.db component) and Connection have the same properties:
Charset Databases Error IgnoreCharset Opened Tables Users Version
and have the same methods:
Begin Close Commit Create Delete Edit Exec Find FormatBlob Limit Open Quote Rollback Subst
The common properties and methods are described in section 22.4.3.
This chapter is dedicated to the special properties of the Connection class:
Host Login Name Password Port Timeout Type User
The Connection class has the special properties
Property | Data type | Description |
---|---|---|
Host | String | Supplies or sets the host on which the database server is located. This host can be a host name or an IP address. The default host is localhost. For SQLite, the host name is the absolute path for the database with this property. |
Login | String | Supplies or sets the DB user that is used to establish the connection. |
User | String | Synonym for the Login property. |
Name | String | Supplies or sets the name of the database to which the DB user should connect. If you do not specify a name, a default system database is used. |
Password | String | Gets the password that is required to establish the connection or sets the password. |
Port | String | Supplies or sets the TCP/IP port that is used to establish the connection. |
Timeout | Integer | Supplies or sets the timeout for establishing the connection in seconds. The default timeout is 20 seconds. |
Type | String | Represents the type of database server or DB library at SQLite with which you want to establish a database connection. |
Table 22.4.1.1.1 : Properties of the Connection class
Notes:
You can use the following procedure to check whether the MySQL or PostgreSQL DB server to which a DB connection is to be established has been started when the programme is started:
'' Determining the status of the DB server<br> '' Argument: DBMS types mysql or postgresql Public Sub DBServerStatus(argType As String) Dim sMessage As String If Not argType Or (Lower(argType) <> "mysql" And Lower(argType) <> "postgresql") Then sMessage = "<b><font size='+1', color='DarkRed'>" sMessage &= ("Error!") sMessage &= "</b></font><hr>" sMessage &= ("The DB server name is missing or has been written incorrectly.") sMessage &= gb.NewLine & gb.NewLine sMessage &= "<b>" & ("The application is therefore terminated!") & "</b>" Message.Error(sMessage) '-- The (main) program is terminated. ------------------------------------------------- Quit Endif Exec ["systemctl", "status", argType] Wait For Read Write '-- EXIT STATUS IN PROCESS.LASTVALUE '------------------------------------------------------------ '-- Documented in `man systemctl` '-- 0 -> program is running or service is OK │ unit is active '-- 3 -> program is not running | unit is not active '-- 4 -> program or service status is unknown │ no such unit Select Case Process.LastValue Case 4 sMessage = "<b><font size='+1', color='DarkRed'>" sMessage &= ("Error!") sMessage &= "</b></font><hr>" sMessage &= Subst("&1 &2 &3", ("The DB server"), Upper(argType), ("is obviously not installed!")) sMessage &= gb.NewLine & gb.NewLine sMessage &= "<b>" & ("The application is therefore terminated!") & "</b>" Message.Error(sMessage) '-- The (main) program is terminated. ----------------------------------------- Quit Case 3 sMessage = "<b><font size='+1', color='DarkRed'>" sMessage &= ("Error!") sMessage &= "</b></font><hr>" sMessage &= Subst("&1 &2 &3", ("The DB server"), Upper(argType), ("is not started!")) sMessage &= gb.NewLine & gb.NewLine sMessage &= "<b>" & ("The application is therefore terminated!") & "</b>" Message.Error(sMessage) '-- The (main) program is terminated. ----------------------------------------- Quit End Select End
To establish a connection to a database, first create a connection object, then set the required properties and then call the 'Open' method. The following section shows you different ways of creating a DB connection. It is assumed that a DB user (name, password) and a database exist for the DBMS used. The database can also be empty - i.e. without DB tables.
Dim hConnection As Connection hConnection = New Connection ( [ DatabaseURL As String ] )
The format of the optional parameter DatabaseURL is
$TYPE://[$USER@]$HOST[:$PORT]/$DBNAME
where the $USER and $PORT parts are optional. However, if this parameter 'DatabaseURL' is specified and valid, the connection properties are set to the transferred property values.
(1) MySQL DB connection (DB user 'test', password 'test', port 3306, database name 'test')
Dim hConnection As Connection hConnection = New Connection("mysql://test@localhost:3306/test") hConnection.Password = "test" Try hConnection.Open() If Error Then Print "The database cannot be opened! Error = "; Error.Text
Alternative:
Dim hConnection As Connection WITH hConnection .Type = "mysql" .Host = "localhost" .User = "test" .Password = "test" .Name = "test" END WITH Try hConnection.Open() If Error Then Print "The database cannot be opened! Error = "; Error.Text
(2) SQLite3 DB connection (database name 'test', path 'User.Home/Test')
Dim hConnection As Connection hConnection = New Connection("sqlite3://" & User.Home /& "Test" &/ "test.sqlite") Try hConnection.Open() If Error Then Print "The database cannot be opened! Error = "; Error.Text
If no DB name is specified, a DB connection to a temporary database is created. Alternatively, you can also use this instruction:
Dim hConnection As Connection hConnection = New Connection("sqlite3://:memory/")
(3) PostgreSQL DB connection (user 'test', password 'test', port 5432, database name 'test')
Dim hConnection As Connection hConnection = New Connection("postgresql://test@localhost:5432/test") hConnection.Password = "test" Try hConnection.Open() If Error Then Print "The database cannot be opened! Error = "; Error.Text
Alternative:
Dim hConnection As Connection WITH hConnection .Type = "postgresql" .Host = "localhost" .Login = "test" .Password = "test" .Name = "test" END WITH Try hConnection.Open() If Error Then Print "The database cannot be opened! Error = "; Error.Text
You can outsource the creation of a DB connection to a module or a static class. This turns the module or static class into a singleton. It ensures that there is only ever one DB connection to a specific database for each database in your programme. The DB connection is established the first time the database is accessed - after that it remains in place during the programme runtime! This ensures that your programme always uses this one DB connection and does not maintain simultaneous connections to the same database, which can lead to database deadlocks. In multitask systems, it would be perfectly possible to keep several DB connections to a database open at the same time. However, this can lead to situations in which one DB connection is waiting for something that is not released in the other DB connection because it is waiting for something that must first be released in the other DB connection.
This is the source code for the static class DBCS, which is always used in all example projects in the book:
[1] ' Gambas class file [2] [3] Create Static [4] [5] Property Read DBConnection As Connection '-- It is a 'DataBaseConnectionSingleton' [6] Private $DBConnection As New Connection [7] [8] Private Function DBConnection_Read() As Connection [9] [10] If Not $DBConnection.Opened Then [11] ' --------------------------------------------------------------------------------------- [12] $DBConnection.Type = "sqlite" [13] $DBConnection.Port = Null [14] $DBConnection.User = Null [15] $DBConnection.Password = Null [16] $DBConnection.Host = MCreateDir.DBHost '-- File-Path for SQLite-Host [17] $DBConnection.Name = "flowers.sqlite" '-- Name of the SQLite database [18] ' --------------------------------------------------------------------------------------- [19] ' $DBConnection.Type = "postgresql" [20] ' $DBConnection.Port = 5432 [21] ' $DBConnection.User = "test" [22] ' $DBConnection.Password = "test" [23] ' $DBConnection.Host = "localhost" '-- DBHost is `localhost ` or an IP adddress [24] ' $DBConnection.Name = "test" '-- Name of the database [25] '---------------------------------------------------------------------------------------- [26] ' $DBConnection.Type = "mysql" [27] ' $DBConnection.Port = 3306 [28] ' $DBConnection.User = "test" [29] ' $DBConnection.Password = "test" [30] ' $DBConnection.Host = "localhost" '-- DBHost is `localhost ` or an IP adddress [31] ' $DBConnection.Name = "test" '-- Name of the database [32] '---------------------------------------------------------------------------------------- [33] [34] If $DBConnection.Type <> "sqlite" Then [35] If $DBConnection.User = Null Or If $DBConnection.Password = Null Then [36] Error.Raise(("No database credentials")) [37] Endif [38] Endif [39] $DBConnection.Open() [40] Endif [41] [42] Return $DBConnection [43] [44] Catch [45] Error.Propagate() [46] [47] End
Example of the use of a DB connection defined in the DBCS class above:
Public Function GetReportData() As Result '-- Returns the result of a database query as a database result. sSQLStatement = "SELECT vorname,nachname,wohnort FROM contats ORDER BY nachname" hDBResult = DBCS.DBConnection.Exec(sSQLStatement) Return hDBResult End
The Gambas IDE offers the option of defining and creating a DB connection (SQLite, MySQL, PostgreSQL, ODBC) for test purposes. If you have selected the gb.db component, a new 'Connections' directory is automatically created in the project directory. You can use its context menu to create a new DB connection in the IDE or update an existing DB connection:
Figure 22.4.1.4.1: Creating a new DB connection to a PostgreSQL database 'test'
If you open a DB connection in the IDE, you can use
Figure 22.4.1.4.2: Overview of DB fields and indices of a DB table (SQLite3)
You can also edit DB data of a selected DB table. However, the prerequisite is that you switch to edit mode (ON/OFF switch).
You can
Figure 22.4.1.4.3: SQL query for an SQLite DB table → Connection1
The option to also make SQL queries for a selected DB table rounds off the scope of work with DB tables for a specific DB connection in the IDE.