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

Fabien Bodard gambas.fr at gmail.com
Wed Nov 29 08:55:32 CET 2017


You can use a self instantiated class...


On the top of the class Use :

CREATE STATIC



The call the class with it's name :

MyClass.Function

2017-11-28 22:50 GMT+01:00 Christof Thalhofer <chrisml at deganius.de>:
> 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:
>
> ---8<-------------------------------
> ' 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")
>         Endif
>         Open($MainDb)
>     Endif
>
>     Return $MainDb
>
> Catch
>     Message.Error(Error.Text)
>
> End
>
> ---8<-------------------------------
>
> This is a "singleton pattern":
>
> https://en.wikipedia.org/wiki/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:
>
> ---8<-------------------------------
> Dim qry As String
> Dim res As Result
>
> qry = "select sthing from tableany;"
> res = Dbs.MainDb.Exec(qry)
> ---8<-------------------------------
>
> 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
>
>
>
> --------------------------------------------------
>
> This is the Gambas Mailing List
> https://lists.gambas-basic.org/listinfo/user
>
> Hosted by https://www.hostsharing.net
>



-- 
Fabien Bodard


More information about the User mailing list