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:

Ogni istanza del servizio Database rappresenta un singolo database e fornisce l'accesso alle sue tabelle, ricerche e dati.

Questo servizio non fornisce accesso ai formulari o ai rapporti del documento di Base che contiene il database. Per accedere ai formulari di un documento di Base, fate riferimento al metodo FormDocuments del servizio Base.

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

Per rendere più leggibili le istruzioni SQL, potete usare le parentesi quadre "[ ]" per racchiudere i nomi di tabelle, ricerche e campi, anziché racchiuderli tra altri caratteri che possono essere di uso esclusivo di determinati RDBMS (Relational Database Management Systems). Prestate comunque attenzione, in questo contesto è obbligatorio usare dei caratteri per racchiudere tali elementi.


Transaction handling

By default the database handles transactions in auto-commit mode, meaning that a commit is done after every SQL statement.

Use the SetTransactionMode method to change the default behavior, which allows for manual commits and rollbacks.

The methods Commit and Rollback are used to delimit transactions.

In LibreOffice, there are five types of transaction isolation modes, as defined in the com.sun.star.sdbc.TransactionIsolation constant group:

Constant

Value

Interpretation

NONE

0

Transaction handling is disabled and the database is set to the default auto-commit mode.

READ_UNCOMMITTED

1

Dirty reads, non-repeatable reads and phantom reads can occur.

If a row is changed by a transaction, another transaction will be able to read these changes even if they have not been committed.

READ_COMMITTED

2

Dirty reads are prevented, however non-repeatable reads and phantom reads can occur.

This level prevents that rows with uncommitted changes are read.

REPEATABLE_READ

4

Dirty reads and non-repeatable reads are prevented. However, phantom reads can occur.

Besides preventing uncommitted data from being read, it also prevents that two read operations in the same transaction return different results.

SERIALIZABLE

8

Dirty reads, non-repeatable reads and phantom reads are prevented.

In addition to the constraints of the previous level, it also ensures that the set of records that match a WHERE clause remains unchanged inside the same transaction.


tip

Read the Wikipedia page on Isolation in Database Systems to learn more about transaction integrity.


Service invocation

Prima di usare il servizio Database è necessario caricare o importare le librerie ScriptForge:

note

• Le macro in Basic richiedono il caricamento della libreria ScriptForge usando la seguente istruzione:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Gli script in Python richiedono un'importazione dal modulo scriptforge:
from scriptforge import CreateScriptService


Sintassi:

Per creare un'istanza del servizio Database potete usare il metodo CreateScriptService:

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

note

Nella sintassi sopra descritta potete usare sia "SFDatabases.Database", sia semplicemente "Database" come primo argomento del metodo CreateScriptService.


Parametri:

filename: il nome del file di Base. Deve essere espresso usando la notazione SF_FileSystem.FileNaming.

registrationname: il nome di un database registrato. Se avete indicato un filename, questo argomento non deve essere usato.

Al contrario, se avete specificato registrationname, il parametro filename non deve essere definito.

readonly: determina se il database sarà aperto in sola lettura (predefinito = True).

user, password: parametri aggiuntivi per la connessione al server del database.

Esempio:

In Basic

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

      from scriptforge import CreateScriptService
      myDatabase = CreateScriptService("Database", "/home/user/Documents/myDB.odb")
      # Esegue ricerche, istruzioni SQL, ...
      myDatabase.CloseDatabase()
    

Accedere ai database con il servizio UI

Potete accedere al database associato al documento di Base anche usando il servizio ScriptForge.UI, come mostrato negli esempi sottostanti:

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()
      ' Esegue ricerche, istruzioni SQL, ...
      myDatabase.CloseDatabase()
      myDoc.CloseDocument()
    
In Python

      ui = CreateScriptService("UI")
      doc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      # Nome utente e password sono fornite di seguito, se necessarie
      myDatabase = doc.GetDatabase()
      # Esegue ricerche, istruzioni SQL, ...
      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

Matrice di stringhe

L'elenco delle ricerche memorizzate.

Tables

Matrice di stringhe

L'elenco delle tabelle memorizzate.

XConnection

XConnection

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

XMetaData

XDatabaseMetaData

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


Elenco dei metodi del servizio Database

CloseDatabase
Commit
CreateDataset
DAvg
DCount
DMin

DMax
DSum
DLookup
GetRows
OpenFormDocument
OpenQuery

OpenSql
OpenTable
Rollback
RunSql
SetTransactionMode


CloseDatabase

Chiude la connessione attiva con il database.

Sintassi:

db.CloseDatabase()

Esempio:


    myDatabase.CloseDatabase() ' Basic
  

    myDatabase.CloseDatabase() # Python
  

Commit

Commits all updates done since the previous Commit or Rollback call.

note

This method is ignored if commits are done automatically after each SQL statement, i.e. the database is set to the default auto-commit mode.


Sintassi:

db.Commit()

Esempio:

In Basic

      ' Set the REPEATABLE_READ transaction level
      myDB.SetTransactionMode(4)
      myDB.RunSql("UPDATE ...")
      myDB.Commit()
      myDB.RunSql("DELETE ...")
      ' Test some condition before committing
      If bSomeCondition Then
          myDB.Commit()
      Else
          myDB.Rollback()
      End If
      ' Restore auto-commit mode
      myDB.SetTransactionMode()
    
In Python

      myDB.SetTransactionMode(4)
      myDB.RunSql("UPDATE ...")
      myDB.Commit()
      myDB.RunSql("DELETE ...")
      if some_condition:
          myDB.Commit()
      else:
          myDB.Rollback()
      myDB.SetTransactionMode()
    

CreateDataset

Creates a Dataset service instance based on a table, query or SQL SELECT statement.

Sintassi:

db.CreateDataset(sqlcommand: str, opt directsql: bool, opt filter: str, opt orderby: str): svc

Parametri:

sqlcommand: A table name, a query name or a valid SQL SELECT statement. Identifiers may be enclosed with square brackets. This argument is case-sensitive.

directsql: Set this argument to True to send the statement directly to the database engine without preprocessing by LibreOffice (Default = False).

filter: Specifies the condition that records must match to be included in the returned dataset. This argument is expressed as a SQL WHERE statement without the "WHERE" keyword.

orderby: Specifies the ordering of the dataset as a SQL ORDER BY statement without the "ORDER BY" keyword.

Esempio:

The following examples in Basic and Python return a dataset with the records of a table named "Customers".

In Basic

      oDataset = myDatabase.CreateDataset("Customers", Filter := "[Name] LIKE 'A'")
    
In Python

      dataset = myDatabase.CreateDataset("Customers", Filter = "[Name] LIKE 'A'")
    

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: un'espressione SQL nella quale i nomi dei campi sono racchiusi tra parentesi quadre.

tablename: il nome di una tabella (senza parentesi quadre).

criteria: una clausola WHERE senza la parola chiave "WHERE", nella quale i nomi dei campi sono racchiusi tra parentesi quadre.

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: un'espressione SQL nella quale i nomi dei campi sono racchiusi tra parentesi quadre.

tablename: il nome di una tabella (senza parentesi quadre).

criteria: una clausola WHERE senza la parola chiave "WHERE", nella quale i nomi dei campi sono racchiusi tra parentesi quadre.

orderclause: una clausola ORDER BY senza le parole chiave "ORDER BY". I nomi dei campi devono essere racchiusi tra parentesi quadre.

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: il nome di una tabella o di una ricerca (senza parentesi quadre) o un'istruzione SELECT in SQL.

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: il numero massimo di righe da restituire. Il valore predefinito è zero, ossia un numero illimitato di righe restituite.

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)
    

OpenFormDocument

Opens the specified form document in normal mode. This method returns a FormDocument service instance corresponding to the specified form document.

If the form document is already open, the form document window is activated.

If the specified form document does not exist, then Nothing is returned.

Sintassi:

svc.OpenFormDocument(formdocument: str): svc

Parametri:

formdocument: The name of the FormDocument to be opened, as a case-sensitive string.

Esempio:

In Basic

Most form documents are stored in the root of the Base document and they can be opened simply using their names, as in the example below:


    Dim oFormDoc As Object
    oFormDoc = myDB.OpenFormDocument("myFormDocument")
  

If form documents are organized in folders, it becomes necessary to include the folder name to specify the form document to be opened, as illustrated in the following example:


    oFormDoc = myDB.OpenFormDocument("myFolder/myFormDocument")
  
In Python

    formDoc = myDB.OpenFormDocument("myFormDocument")
  

    formDoc = myDB.OpenFormDocument("myFolder/myFormDocument")
  

OpenQuery

Apre la finestra Struttura dati della ricerca specificata e restituisce un'istanza del servizio Datasheet.

Se la ricerca non può essere aperta, sarà restituito Nothing.

Sintassi:

db.OpenQuery(queryname: str): obj

Parametri:

queryname: il nome di una ricerca esistente in formato stringa con distinzione tra maiuscole e minuscole.

Esempio:

In Basic

      myDatabase.OpenQuery("MyQuery")
    
In Python

      myDatabase.OpenQuery("MyQuery")
    

OpenSql

Esegue un comando SQL SELECT, apre una finestra Struttura dati con i risultati e restituisce un'istanza del servizio Datasheet.

Sintassi:

db.OpenSql(sql: str, directsql: bool): obj

Parametri:

sql: una stringa contenente un'istruzione SELECT valida in SQL. Gli identificatori possono essere racchiusi in parentesi quadre.

directsql: When True, the SQL command is sent to the database engine without pre-analysis (Default = False).

Esempio:

In Basic

      myDatabase.OpenSql("SELECT * FROM [Customers] ORDER BY [CITY]")
    
In Python

      myDatabase.OpenSql("SELECT * FROM [Customers] ORDER BY [CITY]")
    

OpenTable

Apre la finestra Struttura dati della tabella specificata e restituisce un'istanza del servizio Datasheet.

Sintassi:

db.OpenTable(tablename: str): obj

Parametri:

tablename: il nome di una tabella esistente in formato stringa con distinzione tra maiuscole e minuscole.

Esempio:

In Basic

      myDatabase.OpenTable("MyTable")
    
In Python

      myDatabase.OpenTable("MyTable")
    

Rollback

Cancels all changes made to the database since the last Commit or Rollback call.

Sintassi:

db.Rollback()

Esempio:

In Basic

      myDB.SetTransactionMode(1)
      myDB.RunSql("UPDATE ...")
      ' ...
      If bSomeCondition Then
          myDB.Rollback()
      End If
    
In Python

      myDB.SetTransactionMode(1)
      myDB.RunSql("UPDATE ...")
      # ...
      if bSomeCondition:
          myDB.Rollback()
    

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: il nome di una ricerca (senza parentesi quadre) o un'istruzione SQL.

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)
    

SetTransactionMode

Defines the level of isolation in database transactions.

By default databases manage transactions in auto-commit mode, which means that a Commit is automatically performed after every SQL statement.

Use this method to manually determine the isolation level of transactions. When a transaction mode other than NONE is set, the script has to explicitly call the Commit method to apply the changes to the database.

This method returns True when successful.

warning

Changing the transaction mode closes all Dataset instances created from the current database.


Sintassi:

db.SetTransactionMode(transactionmode: int = 0): bool

Parametri:

transactionmode: Specifies the transaction mode. This argument must be one of the constants defined in com.sun.star.sdbc.TransactionIsolation (Default = NONE)

note

Read the section Transaction handling above to learn more about the transaction isolation levels used in LibreOffice.


Esempio:

In Basic

      myDB.SetTransactionMode(com.sun.star.sdbc.TransactionIsolation.REPEATABLE_READ)
      oDataset = myDB.CreateDataset("SELECT ...")
      ' ...
      ' Reset the transaction mode to default
      myDB.SetTransactionMode()
    
In Python

      from com.sun.star.sdbc import TransactionIsolation
      myDB.SetTransactionMode(TransactionIsolation.REPEATABLE_READ)
      dataset = myDB.CreateDataset("SELECT ...")
      # ...
      myDB.SetTransactionMode()
    
warning

Tutte le routine e gli identificatori Basic di ScriptForge che iniziano con un carattere di sottolineatura "_" sono riservati per uso interno. Non è previsto il loro utilizzo nelle macro in Basic o negli script in Python.