Serviço SFDatabases.Dataset

O serviço Dataset é usado para representar dados tabulares produzidos por um banco de dados. Com este serviço é possível:

warning

Atualizar e inserir registros usando o serviço Dataset é mais lento do que usar instruções SQL. Ao atualizar ou inserir grandes quantidades de registros, é recomendado utilizar instruções SQL em vez de utilizar os métodos deste serviço.


Invocação do serviço

Antes de usar o serviço Dataset a biblioteca ScriptForge precisa ser carregada ou importada:

note

• Macros BASIC precisam carregar a biblioteca ScriptForge usando a seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Scripts Python exigem uma importação do módulo scriptforge:
from scriptforge import CreateScriptService


O serviço Dataset é invocado usando o método CreateDataset, que pode ser chamado de uma instância do serviço Database ou de outra instância Dataset.

Em Basic

O exemplo a seguir cria um Dataset a partir da tabela "Clientes" armazenada em um arquivo de banco de dados.


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

Após a criação do Dataset, o registro atual é posicionado antes do primeiro registro.


O exemplo abaixo cria uma instância do serviço Dataset filtrando o conjunto de dados original.


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

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

    new_dataset = dataset.CreateDataset(filter = "[Cidade]='São Paulo'")
  

Propriedades

Nome

Somente leitura

Tipo

Descrição

BOF

Não

Boolean

Retorna True se a posição atual do registro for anterior ao primeiro registro no conjunto de dados, caso contrário, retorna False.

Defina esta propriedade como True para mover o cursor para o início do conjunto de dados. Definir esta propriedade como False é ignorado.

DefaultValues

Sim

Serviço Dictionary

Retorna uma instância Dictionary com os valores padrão usados para cada campo no conjunto de dados. Os campos ou colunas do conjunto de dados são as chaves do dicionário.

Os tipos de campo do banco de dados são convertidos em seus tipos de dados correspondentes em Basic ou Python. Quando o tipo do campo é indefinido, o valor padrão é Null se o campo for anulável ou Empty caso contrário.

EOF

Não

Boolean

Retorna True se a posição atual do registro for após o último registro no conjunto de dados, caso contrário, retorna False.

Defina esta propriedade como True para mover o cursor para o final do conjunto de dados. Definir esta propriedade como False é ignorado.

Fields

Sim

Array

Retorna um Array contendo os nomes de todos os campos do conjunto de dados.

Filter

Sim

String

Retorna o filtro aplicado além das eventuais cláusulas WHERE na instrução SQL inicial. Esta propriedade é expressa como uma cláusula WHERE sem a palavra-chave "WHERE".

OrderBy

Sim

String

Retorna a cláusula de ordenação que substitui a eventual cláusula ORDER BY presente na instrução SQL inicial. Esta propriedade é expressa como uma cláusula ORDER BY sem as palavras-chave "ORDER BY".

ParentDatabase

Sim

Serviço Database

Retorna a instância Database correspondente ao banco de dados pai do conjunto de dados atual.

RowCount

Sim

Long

Retorna o número exato de registros no conjunto de dados.

Note que a avaliação desta propriedade implica navegar em todo o conjunto de dados, o que pode ser dispendioso dependendo do tamanho do conjunto de dados.

RowNumber

Sim

Long

Retorna o número do registro atual começando em 1. Retorna 0 se esta propriedade for desconhecida.

Source

Sim

String

Retorna a origem do conjunto de dados. Pode ser um nome de tabela, um nome de consulta ou uma instrução SQL.

SourceType

Sim

String

Retorna a origem do conjunto de dados. Pode ser um dos seguintes valores expressos como uma string: TABLE, QUERY ou SQL.

UpdatableFields

Sim

Array

Retorna um Array contendo os nomes dos campos do conjunto de dados que são atualizáveis.

Values

Sim

Array

Retorna um Dictionary contendo os pares (nome do campo: valor) do registro atual no conjunto de dados.

XRowSet

Sim

Objeto UNO

Retorna o objeto UNO com.sun.star.sdb.RowSet que representa o conjunto de dados.


Lista de Métodos no Serviço Dataset

CloseDataset
CreateDataset
Delete
ExportValueToFile
GetRows

GetValue
Insert
MoveFirst
MoveLast

MoveNext
MovePrevious
Reload
Update


CloseDataset

Fecha o conjunto de dados atual. Este método retorna True quando bem-sucedido.

note

Recomenda-se fechar o conjunto de dados após seu uso para liberar recursos.


Sintaxe:

svc.CloseDataset(): bool

Exemplo:

Em Basic

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

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

CreateDataset

Retorna uma instância do serviço Dataset de um conjunto de dados existente aplicando o filtro especificado e instruções ORDER BY.

Sintaxe:

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

Parâmetros:

filter: especifica a condição que os registros devem atender para serem incluídos no conjunto de dados retornado. Este argumento é expresso como uma instrução SQL WHERE sem a palavra-chave "WHERE". Se este argumento não for especificado, então o filtro usado no conjunto de dados atual será aplicado, caso contrário, o filtro atual será substituído por este argumento.

orderby: especifica a ordem do conjunto de dados como uma instrução SQL ORDER BY sem a palavra-chave "ORDER BY". Se este argumento não for especificado, então a ordem de classificação usada no conjunto de dados atual será aplicada; caso contrário, a ordem de classificação atual será substituída por este argumento.

Exemplo:

Em 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'")
    
Em Python

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

Delete

Exclui o registro atual do conjunto de dados. Este método retorna True quando bem-sucedido.

Após esta operação o cursor é posicionado no registro imediatamente após o registro excluído. Se o registro excluído for o último do conjunto de dados, então o cursor é posicionado depois dele e a propriedade EOF retorna True.

Sintaxe:

svc.Delete(): bool

Exemplo:

Em Basic

      oDataset.Delete()
    
Em Python

      dataset.Delete()
    

ExportValueToFile

Exporta o valor de um campo binário do registro atual para o arquivo especificado.

note

Se o campo especificado não for binário ou não contiver dados, o arquivo de saída não será criado.


Sintaxe:

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

Parâmetros:

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).

Exemplo:

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

Em Basic

      oDataset.ExportValueToFile("Picture", "C:\my_image.png", True)
    
Em 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.


Sintaxe:

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

Parâmetros:

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)

Exemplo:

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

Em 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
    
Em 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.


Sintaxe:

svc.GetValue(fieldname: str): any

Parâmetros:

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

Exemplo:

Em Basic

      currId = oDataset.GetValue(FieldName := "ID")
    
Em 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.


Sintaxe:

svc.Insert(pvargs: any): int

Parâmetros:

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.

Exemplo:

Em 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")
    
Em 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.


Sintaxe:

svc.MoveFirst(): bool

svc.MoveLast(): bool

Exemplo:

Em Basic

      oDataset.MoveFirst()
    
Em 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.


Sintaxe:

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

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

Parâmetros:

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

Exemplo:

Em Basic

      oDataset.MoveNext()
      oDataset.MoveNext(5)
    
Em 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.


Sintaxe:

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

Parâmetros:

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.

Exemplo:

Em Basic

      oDataset.Reload()
      oDataset.Reload(Filter := "[Name] = 'John'", OrderBy := "Age")
    
Em 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.

Sintaxe:

svc.Update(pvargs: any): bool

Parâmetros:

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.

Exemplo:

Em 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")
    
Em 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

Todas as rotinas ou identificadores do ScriptForge em Basic que possuem o caractere "_" como prefixo são reservadas para uso interno. Elas não devem ser usadas em macros escritas em Basic ou em Python.