[Gambas-user] how to avoid second instance in hole project

Christof Thalhofer chrisml at deganius.de
Tue Nov 28 22:50:33 CET 2017

Am 28.11.2017 um 18:09 schrieb PICCORO McKAY Lenz:

> we need a common and consistent code and i try to made a common
> lib/module that init the db using config file detected

I do this in my programs in a class called "DBs" like this:

' Gambas class file

Create Static

'' Our Main Database
Property Read MainDb As Connection
Private $MainDb As New Connection

Private Function MainDb_Read() As Connection

    If Not $MainDb.Opened Then
        $MainDb.Type = "postgresql"
        $MainDb.Host = Settings.["MainDb/Host", ""]
        $MainDb.Name = Settings["MainDb/Datenbank", ""]
        $MainDb.Login = Settings["MainDb/User", ""]
        $MainDb.Password = Settings["MainDb/Password"]

        If $MainDb.User = Null And If $MainDb.Password = Null Then
            Error.Raise("No MainDb Credentials")

    Return $MainDb




This is a "singleton pattern":


You can do this also in a module which is a singleton by design.

To use it, you can do anywhere in your program:

Dim qry As String
Dim res As Result

qry = "select sthing from tableany;"
res = Dbs.MainDb.Exec(qry)

On the first usage of Dbs.MainDb it will be instanciated, on every
latter usage the connection will be reused!

This is very safe, as it ensures, that your program always uses this one
 connection and does not do concurrent connections to the same database
(which can lead to database deadlocks ).

Alles Gute

Christof Thalhofer

Dies ist keine Signatur

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20171128/c2f5ccea/attachment.sig>

More information about the User mailing list