SFDatabases.Dataset service/text/sbasic/shared/03/sf_dataset.xhpDataset service
SFDatabases.Dataset service
The Dataset service is used to represent tabular data produced by a database. With this service it is possible to:Navigate through and access the data in a dataset.Update, insert and remove records in a dataset.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.
Service invocation
Before using the Dataset service the ScriptForge library needs to be loaded or imported:The Dataset service is invoked using the CreateDataset method, which can be called either from a Database service instance or from another Dataset instance.The following example creates a Dataset from the table "Customers" stored in a database file.oDatabase = CreateScriptService("Database", "C:\MyDatabase.odb")oDataset = oDatabase.CreateDataset("Customers")With oDataset Do While .MoveNext() oValues = .Values() ' ... Loop .CloseDataset()End WithUpon the creation of the Dataset, the current record is positioned before the first record.The example below creates a Dataset instance by filtering the original dataset.oNewDataset = oDataset.CreateDataset(Filter := "[City]='New York'")database = CreateScriptService("Database", r"C:\MyDatabase.odb")dataset = database.CreateDataset("Customers")while dataset.MoveNext(): values = dataset.Values # ...dataset.CloseDataset()new_dataset = dataset.CreateDataset(filter = "[City]='New York'")Dataset service;BOF propertyDataset service;DefaultValues propertyDataset service;EOF propertyDataset service;Fields propertyDataset service;Filter propertyDataset service;OrderBy propertyDataset service;ParentDatabase propertyDataset service;RowCount propertyDataset service;RowNumber propertyDataset service;Source propertyDataset service;SourceType propertyDataset service;UpdatableFields propertyDataset service;Values propertyDataset service;XRowSet property
Properties
NameReadonlyTypeDescriptionBOFNoBooleanReturns True if the current record position is before the first record in the dataset, otherwise returns False.Set this property to True to move the cursor to the beginning of the dataset. Setting this property to False is ignored.DefaultValuesYesDictionary serviceReturns 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.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.EOFNoBooleanReturns True if the current record position is after the last record in the dataset, otherwise returns False.Set this property to True to move the cursor to the end of the dataset. Setting this property to False is ignored.FieldsYesArrayReturns an Array containing the names of all fields in the dataset.FilterYesStringReturns 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.OrderByYesStringReturns 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.ParentDatabaseYesDatabase serviceReturns the Database instance corresponding to the parent database of the current dataset.RowCountYesLongReturns the exact number of records in the dataset.Note that the evaluation of this property implies browsing the whole dataset, which may be costly depending on the dataset size.RowNumberYesLongReturns the number of the current record starting at 1. Returns 0 if this property is unknown.SourceYesStringReturns the source of the dataset. It can be either a table name, a query name or a SQL statement.SourceTypeYesStringReturns the source of the dataset. It can be one of the following string values: TABLE, QUERY or SQL.UpdatableFieldsYesArrayReturns an Array containing the names of the fields of the dataset that are updatable.ValuesYesArrayReturns a Dictionary containing the pairs (field name: value) of the current record in the dataset.XRowSetYesUNO objectReturns 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
Closes the current dataset. This method returns True when successful.It is recommended to close the dataset after its use to free resources.
svc.CloseDataset(): bool
oDataset = oDatabase.CreateDataset("MyTable")' ...oDataset.CloseDataset()dataset = database.CreateDataset("MyTable")# ...dataset.CloseDataset() CreateDataset -------------------------------------------------------------------------------------- Dataset service;CreateDataset
CreateDataset
Returns a Dataset service instance from an existing dataset by applying the specified filter and order by statements.
svc.CreateDataset(opt filter: str, opt orderby: str): svc
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.' Use an empty string to remove the current filteroNewDataset = oDataset.CreateDataset(Filter := "")' Examples of common filtersoNewDataset = oDataset.CreateDataset(Filter := "[Name] = 'John'")oNewDataset = oDataset.CreateDataset(Filter := "[Name] LIKE 'A'")' It is possible to append additional conditions to the current filteroNewDataset = oDataset.CreateDataset(Filter := "(" & oDataset.Filter & ") AND [Name] LIKE 'A'")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 --------------------------------------------------------------------------------------------- Dataset service;Delete
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.
svc.Delete(): bool
oDataset.Delete()dataset.Delete() ExportValueToFile ----------------------------------------------------------------------------------- Dataset service;ExportValueToFile
ExportValueToFile
Exports the value of a binary field of the current record to the specified file.If the specified field is not binary or if it cointains no data, then the output file is not created.
svc.ExportValueToFile(fieldname: str, filename: str, overwrite: bool): bool
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).In the example below the dataset contains a field named "Picture" that shall be exported to an image file.oDataset.ExportValueToFile("Picture", "C:\my_image.png", True)dataset.ExportValueToFile("Picture", r"C:\my_image.png", True) GetRows -------------------------------------------------------------------------------------------- Dataset service;GetRows
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.The returned array will always have two dimensions, even if the dataset contains a single column and a single record.
svc.GetRows(header: bool, maxrows: int): any
header: Set this argument to True to make the first entry in the Array contain the column headers (Default = False).maxrows: Define the maximum number of records to be returned. If the number of existing records is smaller than maxrows, then the returned array will have only the existing records. Leave this argument blank or set it to zero to return all rows in the dataset (Default = 0)The following example reads a dataset in chunks of 100 rows until all the dataset has been read.Dim arrChunk As Variant, lMaxRows As LonglMaxRows = 100Do arrChunk = oDataset.GetRows(MaxRows := lMaxRows) If UBound(arrChunk, 1) >= 0 Then ' ... End IfLoop Until UBound(arrChunk, 1) < lMaxRows - 1max_rows = 100chunk = dataset.GetRows(maxrows = max_rows)while len(chunk) > 0: # ... chunk = dataset.GetRows(maxrows = max_rows) GetValue ------------------------------------------------------------------------------------------- Dataset service;GetValue
GetValue
Returns the value of the specified field from the current record of the dataset.If the specified field is binary, then its length is returned.
svc.GetValue(fieldname: str): any
fieldname: The name of the field to be returned, as a case-sensitive string.currId = oDataset.GetValue(FieldName := "ID")curr_id = dataset.GetValue(fieldname = "ID") Insert ---------------------------------------------------------------------------------------------- Dataset service;Insert
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).Updatable fields with unspecified values are initialized with their default values.If the specified field is binary, then its length is returned.
svc.Insert(pvargs: any): int
pvargs: A Dictionary containing pairs of field names and their respective values. Alternativelly, an even number of arguments can be specified alternating field names (as a String) and their values.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")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") MoveFirstLast -------------------------------------------------------------------------------------- Dataset service;MoveFirstDataset service;MoveLast
MoveFirst / MoveLast
Moves the dataset cursor to the first (with MoveFirst) or to the last (with MoveLast) record.This method returns True when successful.Deleted records are ignored by this method.
svc.MoveFirst(): bool
svc.MoveLast(): bool
oDataset.MoveFirst()dataset.MoveFirst() MoveNextPrevious ------------------------------------------------------------------------------------ Dataset service;MoveNextDataset service;MovePrevious
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.Deleted records are ignored by this method.
svc.MoveNext(offset: int = 1): bool
svc.MovePrevious(offset: int = 1): bool
offset: The number of records by which the cursor shall be moved forward or backwards. This argument may be a negative value (Default = 1).oDataset.MoveNext()oDataset.MoveNext(5)dataset.MoveNext()dataset.MoveNext(5) Reload --------------------------------------------------------------------------------------------- Dataset service;Reload
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.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.
svc.Reload(opt filter: str, opt orderby: str): bool
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.oDataset.Reload()oDataset.Reload(Filter := "[Name] = 'John'", OrderBy := "Age")dataset.Reload()dataset.Reload(Filter = "[Name] = 'John'", OrderBy = "Age" Update --------------------------------------------------------------------------------------------- Dataset service;Update
Update
Update the values of the specified fields in the current record.This method returns True when successful.
svc.Update(pvargs: any): bool
pvargs: A Dictionary containing pairs of field names and their respective values. Alternativelly, an even number of arguments can be specified alternating field names (as a String) and their values.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")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")