Dienst SFDatabases.Dataset

Der Dienst Dataset wird zur Darstellung tabellarischer Daten verwendet, die von einer Datenbank erstellt werden. Mit diesem Service ist es möglich:

warning

Das Aktualisieren und Einfügen von Datensätzen mit dem Dienst Dataset ist langsamer als die Verwendung von SQL-Anweisungen. Beim Aktualisieren oder Einfügen großer Mengen an Datensätzen wird empfohlen, SQL-Anweisungen anstelle der Methoden in diesem Dienst zu verwenden.


Dienstaufruf

Vor der Verwendung des Dienstes Dataset muss die Bibliothek ScriptForge geladen oder importiert werden:

note

• Grundlegende Makros erfordern das Laden der Bibliothek ScriptForge mit der folgenden Anweisung:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Python-Skripte erfordern einen Import aus dem Modul scriptforge:
from scriptforge import CreateScriptService


Der Dienst Dataset wird mit der Methode CreateDataset aufgerufen, die entweder von einer Dienstinstanz Database oder von einer anderen Instanz Dataset.

In Basic

Im folgenden Beispiel wird ein Dataset aus der in einer Datenbankdatei gespeicherten Tabelle „Kunden“ erstellt.


    oDatabase = CreateScriptService("Database", "C:\MyDatabase.odb")
    oDataset = oDatabase.CreateDataset("Kunden")
    With oDataset
        Do While .MoveNext()
            oValues = .Values()
            ' ...
        Loop
        .CloseDataset()
    End With
  
note

Bei der Erstellung des Dataset wird der aktuelle Datensatz vor dem ersten Datensatz positioniert.


Im folgenden Beispiel wird eine Instanz Dataset erstellt, indem der ursprüngliche Datensatz gefiltert wird.


    oNewDataset = oDataset.CreateDataset(Filter := "[City]='New York'")
  
In Python

    database = CreateScriptService("Database", r"C:\MyDatabase.odb")
    dataset = database.CreateDataset("Kunden")
    while dataset.MoveNext():
        values = dataset.Values
        # ...
    dataset.CloseDataset()
  

    new_dataset = dataset.CreateDataset(filter = "[City]='Berlin'")
  

Eigenschaften

Name

Schreibgeschützt

Typ

Beschreibung

BOF

Nein

Boolean

Gibt True zurück, wenn die aktuelle Datensatzposition vor dem ersten Datensatz im Datensatz liegt, andernfalls wird False zurückgegeben.

Setzt diese Eigenschaft auf True, um den Cursor an den Anfang des Datensatzes zu bewegen. Das Setzen dieser Eigenschaft auf False wird ignoriert.

DefaultValues

Ja

Dienst Dictionary

Gibt ein Dictionary mit den Standardwerten zurück, die für jedes Feld im Datensatz verwendet werden. Die Felder oder Spalten im Datensatz sind die Schlüssel im Wörterbuch.

Die Datenbankfeldtypen werden in die entsprechenden Basic-/Python-Datentypen konvertiert. Wenn der Feldtyp undefiniert ist, ist der Standardwert Null, wenn das Feld nullbar oder Empty ist.

EOF

Nein

Boolean

Gibt True zurück, wenn die aktuelle Datensatzposition nach dem letzten Datensatz im Datensatz liegt, andernfalls wird False zurückgegeben.

Setzen Sie diese Eigenschaft auf True, um den Cursor an das Ende des Datensatzes zu bewegen. Das Setzen dieser Eigenschaft auf False wird ignoriert.

Fields

Ja

Array

Gibt eine Matrix zurück, das die Namen aller Felder im Datensatz enthält.

Filter

Ja

String

Gibt den Filter zurück, der zusätzlich zu den eventuellen Klauseln WHERE in der anfänglichen SQL-Anweisung angewendet wird. Diese Eigenschaft wird als Klausel WHERE ohne das Schlüsselwort "WHERE" ausgedrückt.

OrderBy

Ja

String

Gibt die Sortierklausel zurück, die die eventuelle Klauseln ORDER BY in der ursprünglichen SQL-Anweisung ersetzt. Diese Eigenschaft wird als Klausel ORDER BY ohne die Schlüsselwörter "ORDER BY" ausgedrückt.

ParentDatabase

Ja

Dienst Database

Gibt die Instanz Database zurück, die der übergeordneten Datenbank des aktuellen Datensatzes entspricht.

RowCount

Ja

Long

Gibt die genaue Anzahl der Datensätze im Datensatz zurück.

Beachten Sie, dass die Auswertung dieser Eigenschaft das Durchsuchen des gesamten Datensatzes erfordert, was je nach Datensatzgröße langwierig sein kann.

RowNumber

Ja

Long

Gibt die Nummer des aktuellen Datensatzes beginnend bei 1 zurück. Gibt 0 zurück, wenn diese Eigenschaft unbekannt ist.

Source

Ja

String

Gibt die Quelle des Datensatzes zurück. Dabei kann es sich entweder um einen Tabellennamen, einen Abfragenamen oder eine SQL-Anweisung handeln.

SourceType

Ja

String

Gibt die Quelle des Datensatzes zurück. Es kann eine der folgenden Zeichenfolgen sein: TABLE, QUERY oder SQL.

UpdatableFields

Ja

Array

Gibt eine Matrix zurück, welche die Namen der Felder des Datensatzes enthält, die aktualisierbar sind.

Values

Ja

Array

Gibt ein Dictionary zurück, das die Paare (Feldname:Wert) des aktuellen Datensatzes im Datensatz enthält.

XRowSet

Ja

UNO object

Returns the com.sun.star.sdb.RowSet UNO object representing the dataset.


List of Methods in the Dataset Service

CloseDataset
CreateDataset
Delete
ExportValueToFile
GetRows

GetValue
Insert
MoveFirst
MoveLast

MoveNext
MovePrevious
Reload
Update


CloseDataset

Closes the current dataset. This method returns True when successful.

note

It is recommended to close the dataset after its use to free resources.


Syntax:

svc.CloseDataset(): bool

Beispiel:

In Basic

      oDataset = oDatabase.CreateDataset("MyTable")
      ' ...
      oDataset.CloseDataset()
    
In Python

      dataset = database.CreateDataset("MyTable")
      # ...
      dataset.CloseDataset()
    

CreateDataset

Returns a Dataset service instance from an existing dataset by applying the specified filter and order by statements.

Syntax:

svc.CreateDataset(opt filter: str, opt orderby: str): svc

Parameter:

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. If this argument is not specified, then the filter used in the current dataset is applied, otherwise the current filter is replaced by this argument.

orderby: Specifies the ordering of the dataset as a SQL ORDER BY statement without the "ORDER BY" keyword. If this argument is not specified, then the sorting order used in the current dataset is applied, otherwise the current sorting order is replaced by this argument.

Beispiel:

In Basic

      ' Use an empty string to remove the current filter
      oNewDataset = oDataset.CreateDataset(Filter := "")
      ' Examples of common filters
      oNewDataset = oDataset.CreateDataset(Filter := "[Name] = 'John'")
      oNewDataset = oDataset.CreateDataset(Filter := "[Name] LIKE 'A'")
      ' It is possible to append additional conditions to the current filter
      oNewDataset = oDataset.CreateDataset(Filter := "(" & oDataset.Filter & ") AND [Name] LIKE 'A'")
    
In Python

      new_dataset = dataset.CreateDataset(filter = "")
      new_dataset = dataset.CreateDataset(filter = "[Name] = 'John'")
      new_dataset = dataset.CreateDataset(filter = "[Name] LIKE 'A'")
      new_dataset = dataset.CreateDataset(filter = f"({dataset.Filter}) AND [Name] LIKE 'A'")
    

Delete

Deletes the current record from the dataset. This method returns True when successful.

After this operation the cursor is positioned at the record immediately after the deleted record. If the deleted record is the last in the dataset, then the cursor is positioned after it and the property EOF returns True.

Syntax:

svc.Delete(): bool

Beispiel:

In Basic

      oDataset.Delete()
    
In Python

      dataset.Delete()
    

ExportValueToFile

Exports the value of a binary field of the current record to the specified file.

note

If the specified field is not binary or if it contains no data, then the output file is not created.


Syntax:

svc.ExportValueToFile(fieldname: str, filename: str, overwrite: bool): bool

Parameter:

fieldname: The name of the binary field to be exported, as a case-sensitive string.

filename: The complete path to the file to be created using the notation defined in the FileSystem.FileNaming property.

overwrite: Set this argument to True to allow the destination file to be overwritten (Default = False).

Beispiel:

In the example below the dataset contains a field named "Picture" that shall be exported to an image file.

In Basic

      oDataset.ExportValueToFile("Picture", "C:\my_image.png", True)
    
In Python

      dataset.ExportValueToFile("Picture", r"C:\my_image.png", True)
    

GetRows

Returns the contents of the dataset in a 2-dimensional array, starting from the first record after the current record.

After execution, the cursor is positioned at the row that was last read or after the last record in the dataset, in which case the EOF property returns True.

This method can be used to read data from the dataset in chunks, whose size is defined by the maxrows argument.

note

The returned array will always have two dimensions, even if the dataset contains a single column and a single record.


Syntax:

svc.GetRows(header: bool, maxrows: int): any

Parameter:

header: Set this argument to True to make the first entry in the Array contain the column headers (Default = False).

maxrows: Defines the maximum number of records to be returned. If the number of existing records is smaller than maxrows, then the size of the returned array will be equal to the number of remaining records in the dataset. Leave this argument blank or set it to zero to return all rows in the dataset (Default = 0)

Beispiel:

The following example reads a dataset in chunks of 100 rows until all the dataset has been read.

In Basic

      Dim arrChunk As Variant, lMaxRows As Long
      lMaxRows = 100
      Do
          arrChunk = oDataset.GetRows(MaxRows := lMaxRows)
          If UBound(arrChunk, 1) >= 0 Then
              ' ...
          End If
      Loop Until UBound(arrChunk, 1) < lMaxRows - 1
    
In Python

      max_rows = 100
      chunk = dataset.GetRows(maxrows = max_rows)
      while len(chunk) > 0:
          # ...
          chunk = dataset.GetRows(maxrows = max_rows)
    

GetValue

Returns the value of the specified field from the current record of the dataset.

note

If the specified field is binary, then its length is returned.


Syntax:

svc.GetValue(fieldname: str): any

Parameter:

fieldname: The name of the field to be returned, as a case-sensitive string.

Beispiel:

In Basic

      currId = oDataset.GetValue(FieldName := "ID")
    
In Python

      curr_id = dataset.GetValue(fieldname = "ID")
    

Insert

Inserts a new record at the end of the dataset and initialize its fields with the specified values.

If the primary key of the dataset is an auto value, then this method returns the primary key value of the new record. Otherwise, the method will return 0 (when successful) or -1 (when not successful).

note

Updatable fields with unspecified values are initialized with their default values.


note

If the specified field is binary, then its length is returned.


Syntax:

svc.Insert(pvargs: any): int

Parameter:

pvargs: A Dictionary containing pairs of field names and their respective values. Alternatively, an even number of arguments can be specified alternating field names (as a String) and their values.

Beispiel:

In Basic

Consider a table named "Customers" with 4 fields: "ID" (BigInt, auto value and primary key), "Name" (VarChar), "Age" (Integer), "City" (VarChar).

The example below inserts a new record into this dataset using a Dictionary.


      oDataset = oDatabase.CreateDataset("Customers")
      oNewData = CreateScriptService("Dictionary")
      oNewData.Add("Name", "John")
      oNewData.Add("Age", 50)
      oNewData.Add("City", "Chicago")
      lNewID = oDataset.Insert(oNewData)
    

The same result can be achieved by passing all pairs of fields and values as arguments:


      oDataset.Insert("Name", "John", "Age", 50, "City", "Chicago")
    
In Python

      dataset = database.CreateDataset("Customers")
      new_data = {"Name": "John", "Age": 30, "City": "Chicago"}
      new_id = dataset.Insert(new_data)
    

The following calls are accepted in Python:


      dataset.Insert("Name", "John", "Age", 50, "City", "Chicago")
      dataset.Insert(Name = "John", Age = 50, City = "Chicago")
    

MoveFirst / MoveLast

Moves the dataset cursor to the first (with MoveFirst) or to the last (with MoveLast) record.

This method returns True when successful.

note

Deleted records are ignored by this method.


Syntax:

svc.MoveFirst(): bool

svc.MoveLast(): bool

Beispiel:

In Basic

      oDataset.MoveFirst()
    
In Python

      dataset.MoveFirst()
    

MoveNext / MovePrevious

Moves the dataset cursor forward (with MoveNext) or backwards (with MovePrevious) by a given number of records.

This method returns True when successful.

note

Deleted records are ignored by this method.


Syntax:

svc.MoveNext(offset: int = 1): bool

svc.MovePrevious(offset: int = 1): bool

Parameter:

offset: The number of records by which the cursor shall be moved forward or backwards. This argument may be a negative value (Default = 1).

Beispiel:

In Basic

      oDataset.MoveNext()
      oDataset.MoveNext(5)
    
In Python

      dataset.MoveNext()
      dataset.MoveNext(5)
    

Reload

Reloads the dataset from the database. The properties Filter and OrderBy may be defined when calling this method.

This method returns True when successful.

tip

Reloading the dataset is useful when records have been inserted to or deleted from the database. Note that the methods CreateDataset and Reload perform similar functions, however Reload reuses the same Dataset class instance.


Syntax:

svc.Reload(opt filter: str, opt orderby: str): bool

Parameter:

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. If this argument is not specified, then the filter used in the current dataset is applied, otherwise the current filter is replaced by this argument.

orderby: Specifies the ordering of the dataset as a SQL ORDER BY statement without the "ORDER BY" keyword. If this argument is not specified, then the sorting order used in the current dataset is applied, otherwise the current sorting order is replaced by this argument.

Beispiel:

In Basic

      oDataset.Reload()
      oDataset.Reload(Filter := "[Name] = 'John'", OrderBy := "Age")
    
In Python

      dataset.Reload()
      dataset.Reload(Filter = "[Name] = 'John'", OrderBy = "Age")
    

Update

Update the values of the specified fields in the current record.

This method returns True when successful.

Syntax:

svc.Update(pvargs: any): bool

Parameter:

pvargs: A Dictionary containing pairs of field names and their respective values. Alternatively, an even number of arguments can be specified alternating field names (as a String) and their values.

Beispiel:

In Basic

The example below updates the current record using a Dictionary.


      oNewValues = CreateScriptService("Dictionary")
      oNewValues.Add("Age", 51)
      oNewValues.Add("City", "New York")
      oDataset.Update(oNewValues)
    

The same result can be achieved by passing all pairs of fields and values as arguments:


      oDataset.Update("Age", 51, "City", "New York")
    
In Python

      new_values = {"Age": 51, "City": "New York"}
      dataset.Update(new_values)
    

      dataset.Update("Age", 51, "City", "New York")
      dataset.Update(Age = 51, City = "New York")
    
warning

Alle ScriptForge Basic-Routinen oder Bezeichner, denen ein Unterstrich "_" vorangestellt ist, sind für den internen Gebrauch reserviert. Sie sind nicht für die Verwendung in Basic-Makros oder Python-Skripten vorgesehen.