SFDatabases.Database service

The Database service provides access to databases either embedded or described in Base documents. This service provides methods to:

Each instance of the Database service represents a single database and gives access to its tables, queries and data.

This service does not provide access to forms or reports in the Base document that contains the database. To access forms in a Base document, refer to the method FormDocuments of the Base service.

note

All exchanges between this service and the database are done using SQL only.


SQL statements may be run in direct or indirect mode. In direct mode the statement is transferred to the database engine without any syntax checking or review.

The provided interfaces include simple tables and queries lists, as well as access to database data.

tip

To make SQL statements more readable, you may use square brackets "[ ]" to enclose names of tables, queries and fields instead of using other enclosing characters that may be exclusive to certain Relational Database Management Systems (RDBMS). But beware that enclosing characters are mandatory in this context.


Invocación del servicio

Antes de utilizar el servicio Database, es necesario cargar o importar la biblioteca ScriptForge:

note

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Los scripts de Python necesitan importar el módulo scriptforge:
from scriptforge import CreateScriptService


Sintaxis:

To create a instance of the Database service you can use the CreateScriptService method:

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

note

In the syntax described above you can use either "SFDatabases.Database" or simply "Database" as the first argument of the CreateScriptService method.


Parámetros:

filename: The name of the Base file. Must be expressed using SF_FileSystem.FileNaming notation.

registrationname: The name of a registered database. If filename is provided, this argument should not be used.

Conversely, if a registrationname is specified, the filename parameter should not be defined.

readonly: Determines if the database will be opened as readonly (Default = True).

user, password: Additional connection parameters to the database server.

Ejemplo:

En BASIC

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim myDatabase as Object
      Set myDatabase = CreateScriptService("Database", "/home/user/Documents/myDB.odb")
      ' Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
    
En Python

      from scriptforge import CreateScriptService
      myDatabase = CreateScriptService("Database", "/home/user/Documents/myDB.odb")
      # Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
    

Accessing Databases with the UI Service

It is also possible to access the database associated with a Base document using the ScriptForge.UI service, as shown in the examples below:

En BASIC

      Dim myDoc As Object, myDatabase As Object, ui As Object
      Set ui = CreateScriptService("UI")
      Set myDoc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      ' A continuación se proporcionan el usuario y la contraseña, si hicieran falta
      Set myDatabase = myDoc.GetDatabase()
      ' Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
      myDoc.CloseDocument()
    
En Python

      ui = CreateScriptService("UI")
      doc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      # User and password are supplied below, if needed
      myDatabase = doc.GetDatabase()
      # Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
      doc.CloseDocument()
    
tip

The GetDatabase method used in the example above is part of ScriptForge's Base service.


Propiedades

Nombre

De solo lectura

Tipo

Descripción

Queries

Matriz de cadenas

La lista de consultas almacenadas.

Tables

Matriz de cadenas

La lista de tablas almacenadas.

XConnection

XConnection

El objeto UNO que representa la conexión de base de datos actual.

XMetaData

XDatabaseMetaData

El objeto UNO que representa los metadatos que describen los atributos del sistema de base de datos.


Lista de métodos en el servicio Database

CloseDatabase
DAvg
DCount

DMin
DMax
DSum

DLookup
GetRows
RunSql


CloseDatabase

Cierra la conexión actual con la base de datos.

Sintaxis:

db.CloseDatabase()

Ejemplo:


    myDatabase.CloseDatabase() ' Basic
  

    myDatabase.CloseDatabase() # Python
  

DAvg, DCount, DMin, DMax, DSum

Calcula la función de totalización en un campo o una expresión perteneciente a una tabla.

Optionally, a SQL WHERE clause can be specified as a filter that will be applied prior to the aggregate function.

Sintaxis:

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

Parámetros:

expression: A SQL expression in which the field names are surrounded with square brackets.

tablename: A table name (without square brackets).

criteria: A WHERE clause without the "WHERE" keyword, in which field names are surrounded with square brackets.

Ejemplo:

The example below assumes the file Employees.odb has a table named EmployeeData.

En BASIC

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim myDB as Variant
      Set myDB = CreateScriptService("Database", "/home/user/Databases/Employees.odb")
      ' Cuenta todos los empleados en la tabla
      MsgBox myDB.DCount("[ID]", "EmployeeData")
      ' Devuelve la suma de todos los salarios en la tabla
      MsgBox myDB.DSum("[Salary]", "EmployeeData")
      ' Below are some examples of how tables can be filtered
      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%'")
    
En 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

Computes a SQL expression on a single record returned by a WHERE clause defined by the Criteria parameter.

If the query returns multiple records, only the first one is considered. Use the OrderClause parameter to determine how query results are sorted.

Sintaxis:

db.DLookup(expression: str, tablename: str, [criteria:str], [orderclause: str]): any

Parámetros:

expression: A SQL expression in which the field names are surrounded with square brackets.

tablename: A table name (without square brackets).

criteria: A WHERE clause without the "WHERE" keyword, in which field names are surrounded with square brackets.

orderclause: An ORDER BY clause without the "ORDER BY" keywords. Field names should be surrounded with square brackets.

Ejemplo:

En 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'")
    
En 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

Stores the contents of a table or the results of a SELECT query or of an SQL statement in a two-dimensional array. The first index in the array corresponds to the rows and the second index refers to the columns.

An upper limit can be specified to the number of returned rows. Optionally column names may be inserted in the first row of the array.

The returned array will be empty if no rows are returned and the column headers are not required.

Sintaxis:

db.GetRows(sqlcommand: str, directsql: bool = False, header: bool = False, maxrows: int = 0): any

Parámetros:

sqlcommand: A table or query name (without square brackets) or a SELECT SQL statement.

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: The maximum number of rows to return. The default is zero, meaning there is no limit to the number of returned rows.

Ejemplo:

A continuación se proporcionan algunos ejemplos de uso del método GetRows:

En BASIC

      Dim queryResults as Variant
      ' Returns all rows in the table with column headers
      queryResults = myDB.GetRows("EmployeeData", Header := True)
      ' Returns the first 50 employee records ordered by the 'FirstName' field
      queryResults = myDB.GetRows("SELECT * FROM EmployeeData ORDER BY [FirstName]", MaxRows := 50)
    
En Python

      queryResults = myDB.GetRows("EmployeeData", header = True)
      queryResults = myDB.GetRows("SELECT * FROM EmployeeData ORDER BY [FirstName]", maxrows = 50)
    

RunSql

Executes an action query of an SQL statement such as creating a table, as well as inserting, updating and deleting records.

The method returns True when successful.

tip

The RunSql method is rejected with an error message in case the database was previously opened in read-only mode.


Sintaxis:

db.RunSql(sqlcommand: str, directsql: bool = False): bool

Parámetros:

sqlcommand: A query name (without square brackets) or a SQL statement.

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.

Ejemplo:

En BASIC

      myDatabase.RunSql("INSERT INTO [EmployeeData] VALUES(25, 'Smith', 'John')", DirectSQL := True)
    
En Python

      myDatabase.RunSql("INSERT INTO [EmployeeData] VALUES(25, 'Smith', 'John')", directsql = True)
    
warning

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.


¡Necesitamos su ayuda!