3tsWM‖

p9Y5W‖SFDatabases.Dataset service

CmkuE‖The Dataset service is used to represent tabular data produced by a database. With this service it is possible to:

warning

rByVk‖Updating and inserting records using the Dataset service is slower than using SQL statements. When updating or inserting large amounts of records, it is recommended to use SQL statements instead of using the methods in this service.


WAVCq‖Service invocation

HqBAw‖Before using the Dataset service the ScriptForge library needs to be loaded or imported:

note

gF8D8‖• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService


dBCRY‖The Dataset service is invoked using the CreateDataset method, which can be called either from a Database service instance or from another Dataset instance.

3aa4B‖In Basic

uB7FC‖The following example creates a Dataset from the table "Customers" stored in a database file.


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

kjDBm‖Upon the creation of the Dataset, the current record is positioned before the first record.


5RQVs‖The example below creates a Dataset instance by filtering the original dataset.


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

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

    vvGTe‖new_dataset = dataset.CreateDataset(filter = "[City]='New York'")
  

UbDcm‖Properties

9jpZ5‖Name

wYVH2‖Readonly

BzGFs‖Type

uDWJe‖Description

BOF

vvCt8‖No

Boolean

tbT3C‖Returns True if the current record position is before the first record in the dataset, otherwise returns False.

EteGE‖Set this property to True to move the cursor to the beginning of the dataset. Setting this property to False is ignored.

DefaultValues

Bqkq3‖Yes

PPmEj‖Dictionary service

CQWtE‖Returns a Dictionary with the default values used for each field in the dataset. The fields or columns in the dataset are the keys in the dictionary.

3hnoA‖The database field types are converted to their corresponding Basic/Python data types. When the field type is undefined, the default value is Null if the field is nullable or Empty.

EOF

9f7Zn‖No

Boolean

5DCq8‖Returns True if the current record position is after the last record in the dataset, otherwise returns False.

A4QYe‖Set this property to True to move the cursor to the end of the dataset. Setting this property to False is ignored.

Fields

FXQzh‖Yes

Array

pKHRj‖Returns an Array containing the names of all fields in the dataset.

Filter

iDYwc‖Yes

String

2wGrC‖Returns the filter applied in addition to the eventual WHERE clause(s) in the initial SQL statement. This property is expressed as a WHERE clause without the "WHERE" keyword.

OrderBy

niyhC‖Yes

String

QyUBG‖Returns the ordering clause that replaces the eventual ORDER BY clause present in the initial SQL statement. This property is expressed as a ORDER BY clause without the "ORDER BY" keywords.

ParentDatabase

4qKPb‖Yes

SCZG6‖Database service

TCDSW‖Returns the Database instance corresponding to the parent database of the current dataset.

RowCount

SBPcF‖Yes

Long

HoZCK‖Returns the exact number of records in the dataset.

CYZ2R‖Note that the evaluation of this property implies browsing the whole dataset, which may be costly depending on the dataset size.

RowNumber

8SziE‖Yes

Long

ExPSX‖Returns the number of the current record starting at 1. Returns 0 if this property is unknown.

Source

3tm4G‖Yes

String

ZTuFP‖Returns the source of the dataset. It can be either a table name, a query name or a SQL statement.

SourceType

bGyUH‖Yes

String

doL3q‖Returns the source of the dataset. It can be one of the following string values: TABLE, QUERY or SQL.

UpdatableFields

cA9pt‖Yes

Array

XYGFy‖Returns an Array containing the names of the fields of the dataset that are updatable.

Values

F6ZCq‖Yes

Array

ykZky‖Returns a Dictionary containing the pairs (field name: value) of the current record in the dataset.

XRowSet

aao9u‖Yes

hTAUU‖UNO object

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


DCeqW‖List of Methods in the Dataset Service

CloseDataset
CreateDataset
Delete
ExportValueToFile
GetRows

GetValue
Insert
MoveFirst
MoveLast

MoveNext
MovePrevious
Reload
Update


DS9tn‖

CloseDataset

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

note

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


FVEx2‖Syntax:

svc.CloseDataset(): bool

EFSA4‖Example:

3aa4B‖In Basic

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

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

CreateDataset

pB3e6‖Returns a Dataset service instance from an existing dataset by applying the specified filter and ORDER BY statements.

FVEx2‖Syntax:

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

WADQ4‖Parameters:

sTshg‖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.

96FYs‖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.

EFSA4‖Example:

3aa4B‖In Basic

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

      new_dataset = dataset.CreateDataset(filter = "")
      3GUnc‖new_dataset = dataset.CreateDataset(filter = "[Name] = 'John'")
      FfGsf‖new_dataset = dataset.CreateDataset(filter = "[Name] LIKE 'A'")
      xFhtG‖new_dataset = dataset.CreateDataset(filter = f"({dataset.Filter}) AND [Name] LIKE 'A'")
    
hEL8w‖

Delete

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

DeLNv‖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.

FVEx2‖Syntax:

svc.Delete(): bool

EFSA4‖Example:

3aa4B‖In Basic

      oDataset.Delete()
    
BenDd‖In Python

      dataset.Delete()
    
C4TzE‖

ExportValueToFile

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

note

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


FVEx2‖Syntax:

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

WADQ4‖Parameters:

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

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

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

EFSA4‖Example:

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

3aa4B‖In Basic

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

      HSjEn‖dataset.ExportValueToFile("Picture", r"C:\my_image.png", True)
    
5dKNG‖

GetRows

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

wKNGY‖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.

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

note

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


FVEx2‖Syntax:

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

WADQ4‖Parameters:

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

Rnc4L‖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)

EFSA4‖Example:

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

3aa4B‖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
    
BenDd‖In Python

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

GetValue

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

note

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


FVEx2‖Syntax:

svc.GetValue(fieldname: str): any

WADQ4‖Parameters:

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

EFSA4‖Example:

3aa4B‖In Basic

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

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

Insert

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

HQzFF‖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

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


note

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


FVEx2‖Syntax:

svc.Insert(pvargs: any): int

WADQ4‖Parameters:

hzFC6‖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.

EFSA4‖Example:

3aa4B‖In Basic

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

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


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

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


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

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

PL6Tb‖The following calls are accepted in Python:


      iVyAx‖dataset.Insert("Name", "John", "Age", 50, "City", "Chicago")
      SSUPT‖dataset.Insert(Name = "John", Age = 50, City = "Chicago")
    
hhcWb‖

MoveFirst / MoveLast

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

MNACy‖This method returns True when successful.

note

9vNrm‖Deleted records are ignored by this method.


FVEx2‖Syntax:

svc.MoveFirst(): bool

svc.MoveLast(): bool

EFSA4‖Example:

3aa4B‖In Basic

      oDataset.MoveFirst()
    
BenDd‖In Python

      dataset.MoveFirst()
    
AzEb2‖

MoveNext / MovePrevious

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

ZgZBd‖This method returns True when successful.

note

P3w8A‖Deleted records are ignored by this method.


FVEx2‖Syntax:

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

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

WADQ4‖Parameters:

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

EFSA4‖Example:

3aa4B‖In Basic

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

      dataset.MoveNext()
      dataset.MoveNext(5)
    
djTNq‖

Reload

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

qTLq2‖This method returns True when successful.

tip

4N2Sk‖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.


FVEx2‖Syntax:

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

WADQ4‖Parameters:

BeqeG‖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.

7kCWx‖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.

EFSA4‖Example:

3aa4B‖In Basic

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

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

Update

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

9y7wT‖This method returns True when successful.

FVEx2‖Syntax:

svc.Update(pvargs: any): bool

WADQ4‖Parameters:

AuDhR‖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.

EFSA4‖Example:

3aa4B‖In Basic

UpZsi‖The example below updates the current record using a Dictionary.


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

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


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

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

      oWPDV‖dataset.Update("Age", 51, "City", "New York")
      8RvfD‖dataset.Update(Age = 51, City = "New York")
    
warning

uzETY‖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.