Servizio SFDatabases.Database

Il servizio Database fornisce l'accesso sia ai database incorporati, sia a quelli descritti nei documenti di Base. Questo servizio fornisce metodi per:

Each instance of the Database service represents a single database and gives access to its tables, queries and data.

This service does not provide access to forms or reports in the Base document that contains the database. To access forms in a Base document, refer to the method FormDocuments of the Base service.

note

Tutti le transazioni tra questo servizio e il database sono eseguite usando esclusivamente SQL.


Le istruzioni SQL possono essere eseguite in modalità diretta o indiretta. In modalità diretta l'istruzione viene trasferita al motore del database senza alcun controllo della sintassi o revisione.

Le interfacce fornite comprendono semplici elenchi di tabelle e ricerche, così come l'accesso ai dati del database.

tip

To make SQL statements more readable, you may use square brackets "[ ]" to enclose names of tables, queries and fields instead of using other enclosing characters that may be exclusive to certain Relational Database Management Systems (RDBMS). But beware that enclosing characters are mandatory in this context.


Invocare il servizio

Sintassi:

To create a instance of the Database service you can use the CreateScriptService method:

CreateScriptService("SFDatabases.Database", [filename: str], [registrationname], [readonly], [user, [password]]): svc

note

In the syntax described above you can use either "SFDatabases.Database" or simply "Database" as the first argument of the CreateScriptService method.


Parametri:

filename: The name of the Base file. Must be expressed using SF_FileSystem.FileNaming notation.

registrationname: The name of a registered database. If filename is provided, this argument should not be used.

Conversely, if a registrationname is specified, the filename parameter should not be defined.

readonly: Determines if the database will be opened as readonly (Default = True).

user, password: Additional connection parameters to the database server.

Esempio:

In Basic

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim myDatabase as Object
      Set myDatabase = CreateScriptService("Database", "/home/user/Documents/myDB.odb")
      ' Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
    
In Python

      from scriptforge import CreateScriptService
      myDatabase = CreateScriptService("Database", "/home/user/Documents/myDB.odb")
      # Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
    

Accedere ai database con il servizio UI

It is also possible to access the database associated with a Base document using the ScriptForge.UI service, as shown in the examples below:

In Basic

      Dim myDoc As Object, myDatabase As Object, ui As Object
      Set ui = CreateScriptService("UI")
      Set myDoc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      ' Utente e password sono fornite di seguito, se necessarie
      Set myDatabase = myDoc.GetDatabase()
      ' Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
      myDoc.CloseDocument()
    
In Python

      ui = CreateScriptService("UI")
      doc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      # User and password are supplied below, if needed
      myDatabase = doc.GetDatabase()
      # Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
      doc.CloseDocument()
    
tip

Il metodo GetDatabase usato nell'esempio precedente fa parte del servizio Base di ScriptForge.


Proprietà

Nome

Sola lettura

Tipo

Descrizione

Queries

Sì

Matrice di stringhe

L'elenco delle ricerche memorizzate.

Tables

Sì

Matrice di stringhe

L'elenco delle tabelle memorizzate.

XConnection

Sì

XConnection

L'oggetto UNO che rappresenta la connessione attiva con il database.

XMetaData

Sì

XDatabaseMetaData

L'oggetto UNO che rappresenta i metadati che descrivono gli attributi di sistema del database.


Elenco dei metodi del servizio Database

CloseDatabase
DAvg
DCount

DMin
DMax
DSum

DLookup
GetRows
RunSql


CloseDatabase

Chiude la connessione attiva con il database.

Sintassi:

db.CloseDatabase()

Esempio:


    myDatabase.CloseDatabase() ' Basic
  

    myDatabase.CloseDatabase() # Python
  

DAvg, DCount, DMin, DMax, DSum

Calcola la funzione aggregata specificata per un campo o un'espressione appartenente a una tabella.

Facoltativamente è possibile specificare una clausola WHERE di SQL come filtro da applicare prima della funzione aggregata.

Sintassi:

db.DAvg(expression: str, tablename: str, [criteria: str]): any

db.DCount(expression: str, tablename: str, [criteria: str]): any

db.DMin(expression: str, tablename: str, [criteria: str]): any

db.DMax(expression: str, tablename: str, [criteria: str]): any

db.DSum(expression: str, tablename: str, [criteria: str]): any

Parametri:

expression: A SQL expression in which the field names are surrounded with square brackets.

tablename: A table name (without square brackets).

criteria: A WHERE clause without the "WHERE" keyword, in which field names are surrounded with square brackets.

Esempio:

L'esempio sottostante presuppone che il file Employees.odb contenga una tabella denominata EmployeeData.

In Basic

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim myDB as Variant
      Set myDB = CreateScriptService("Database", "/home/user/Databases/Employees.odb")
      'Conta il numero di dipendenti nella tabella
      MsgBox myDB.DCount("[ID]", "EmployeeData")
      ' Restituisce la somma di tutti i salari nella tabella
      MsgBox myDB.DSum("[Salary]", "EmployeeData")
      'Di seguito trovate alcuni esempi di come si possono filtrare le tabelle
      MsgBox myDB.DCount("[ID]", "EmployeeData", "[Position] = 'Manager'")
      MsgBox myDB.DCount("[ID]", "EmployeeData", "[Position] = 'Sales' AND [City] = 'Chicago'")
      MsgBox myDB.DCount("[ID]", "EmployeeData", "[FirstName] LIKE 'Paul%'")
    
In Python

      myDB = CreateScriptService("Database", "/home/user/Databases/Employees.odb")
      bas = CreateScriptService("Basic")
      bas.MsgBox(myDB.DCount("[ID]", "EmployeeData"))
      bas.MsgBox(myDB.DSum("[Salary]", "EmployeeData"))
      bas.MsgBox(myDB.DCount("[ID]", "EmployeeData", "[Position] = 'Manager'"))
      bas.MsgBox(myDB.DCount("[ID]", "EmployeeData", "[Position] = 'Sales' AND [City] = 'Chicago'"))
      bas.MsgBox(myDB.DCount("[ID]", "EmployeeData", "[FirstName] LIKE 'Paul%'"))
    

DLookup

Calcola un'espressione SQL su di un singolo record restituito dalla clausola WHERE definita nel parametro Criteria.

Se la ricerca restituisce più record, viene considerato solamente il primo. Usate il parametro OrderClause per stabilire come vanno ordinati i risultati della ricerca.

Sintassi:

db.DLookup(expression: str, tablename: str, [criteria:str], [orderclause: str]): any

Parametri:

expression: A SQL expression in which the field names are surrounded with square brackets.

tablename: A table name (without square brackets).

criteria: A WHERE clause without the "WHERE" keyword, in which field names are surrounded with square brackets.

orderclause: An ORDER BY clause without the "ORDER BY" keywords. Field names should be surrounded with square brackets.

Esempio:

In Basic

      MsgBox myDB.DLookup("[FirstName]", "EmployeeData", Criteria := "[LastName] LIKE 'Smith'", OrderClause := "[FirstName] DESC")
      MsgBox myDB.DLookup("[Salary]", "EmployeeData", Criteria := "[ID] = '3'")
      MsgBox myDB.DLookup("[Quantity] * [Value]", "Sales", Criteria := "[SaleID] = '5014'")
    
In Python

      bas = CreateScriptService("Basic")
      bas.MsgBox(myDB.DLookup("[FirstName]", "EmployeeData", criteria = "[LastName] LIKE 'Smith'", orderclause = "[FirstName] DESC"))
      bas.MsgBox(myDB.DLookup("[Salary]", "EmployeeData", criteria = "[ID] = '3'"))
      bas.MsgBox(myDB.DLookup("[Quantity] * [Value]", "Sales", criteria = "[SaleID] = '5014'"))
    

GetRows

Memorizza in una matrice bidimensionale i contenuti di una tabella o i risultati di una ricerca con SELECT o di un'istruzione SQL. Il primo indice della matrice corrisponde alle righe e il secondo si riferisce alle colonne.

È possibile specificare un limite massimo al numero di righe che vengono restituite. Opzionalmente è possibile inserire i nomi delle colonne nella prima riga della matrice.

La matrice restituita sarà vuota se non viene restituita alcuna riga e le intestazioni di colonna non sono richieste.

Sintassi:

db.GetRows(sqlcommand: str, directsql: bool = False, header: bool = False, maxrows: int = 0): any

Parametri:

sqlcommand: A table or query name (without square brackets) or a SELECT SQL statement.

directsql: When True, the SQL command is sent to the database engine without pre-analysis. Default is False. This argument is ignored for tables. For queries, the applied option is the one set when the query was defined.

header: When True, the first row of the returned array contains the column headers.

maxrows: The maximum number of rows to return. The default is zero, meaning there is no limit to the number of returned rows.

Esempio:

Di seguito trovata alcuni esempi di come può essere usato il metodo GetRows:

In Basic

      Dim queryResults as Variant
      ' Restituisce tutte le righe di una tabella con le intestazioni di colonna
      queryResults = myDB.GetRows("EmployeeData", Header := True)
      ' Restituisce i primi 50 record dei dipendenti ordinati in base al campo 'FirstName'
      queryResults = myDB.GetRows("SELECT * FROM EmployeeData ORDER BY [FirstName]", MaxRows := 50)
    
In Python

      queryResults = myDB.GetRows("EmployeeData", header = True)
      queryResults = myDB.GetRows("SELECT * FROM EmployeeData ORDER BY [FirstName]", maxrows = 50)
    

RunSql

Esegue una ricerca attiva di un'istruzione SQL come la creazione di una tabella, oppure l'inserimento, la modifica e l'eliminazione di record.

Il metodo restituisce True, se eseguito correttamente.

tip

Il metodo RunSql viene respinto con un messaggio di errore nel caso in cui il database in precedenza era stato aperto in modalità di sola lettura.


Sintassi:

db.RunSql(sqlcommand: str, directsql: bool = False): bool

Parametri:

sqlcommand: A query name (without square brackets) or a SQL statement.

directsql: When True, the SQL command is sent to the database engine without pre-analysis. (Default = False). For queries, the applied option is the one set when the query was defined.

Esempio:

In Basic

      myDatabase.RunSql("INSERT INTO [EmployeeData] VALUES(25, 'Smith', 'John')", DirectSQL := True)
    
In Python

      myDatabase.RunSql("INSERT INTO [EmployeeData] VALUES(25, 'Smith', 'John')", directsql = True)
    
warning

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.