Tenesta SFDatabases.Database

Tenesta Database gjev tilgang til databasar anten innebygde eller omtalte i Base-dokument. Denne tenesta leverer metodar til:

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

Alle utvekslingar mellom denne tenesta og databasen vert gjort berre ved hjelp av SQL.


SQL-uttrykk kan køyrast i direct (direkte) eller indirect (indirekte) modus. I direkte tilstand vert uttrykket overført til databasemotoren utan kontroll av syntaksen eller gjennomsyn.

Grensesnitta som føljer med, inkluderer enkle tabellar og spørjingar i tillegg til tilgang til databasedata.

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.


Oppkall av tenester

Before using the Database service the ScriptForge library needs to be loaded or imported:

note

• 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


Syntaks:

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.


Parametrar:

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.

Eksempel:

I Basic

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

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

Tilgang til databasen med tenesta UI

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

I Basic

      Dim myDoc As Object, myDatabase As Object, ui As Object
      Set ui = CreateScriptService("UI")
      Set myDoc = ui.OpenBaseDocument("/home/user/Documents/myDB.odb")
      ' Brukar og passord vert oppgjeve nedanfor om nødvendig
      Set myDatabase = myDoc.GetDatabase()
      ' Run queries, SQL statements, ...
      myDatabase.CloseDatabase()
      myDoc.CloseDocument()
    
I 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.


Eigenskapar

Namn

Skriveverna

Type

Beskriving

Queries

Ja

Matrise av strengar

Lista over lagra spørjingar.

Tables

Ja

Matrise av strengar

Lista over lagra tabellar.

XConnection

Ja

XConnection

UNO-objektet som representerer den gjeldande databasekoplinga.

XMetaData

Ja

XDatabaseMetaData

UNO-objektet som representerer metadataa som forklarer attributta for databasesystemet.


Liste over metodar i tenesta database

CloseDatabase
DAvg
DCount

DMin
DMax
DSum

DLookup
GetRows
RunSql


CloseDatabase

Lukkar den gjeldande databasekoplinga.

Syntaks:

db.CloseDatabase()

Eksempel:


    myDatabase.CloseDatabase() ' Basic
  

    myDatabase.CloseDatabase() # Python
  

DAvg, DCount, DMin, DMax, DSum

Reknar ut den gjevne samandragsfunksjonen for eit felt eller uttrykk som høyrer til ein tabell.

Ein SQL WHERE-setningsdel kan eventuelt setjast som eit filter som skal brukast før samandragsfunksjonen

Syntaks:

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

Parametrar:

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.

Eksempel:

Eksempelet nedanfor går ut frå at fila Employees.odb har ein tabell med namnet EmployeeData.

I Basic

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim myDB as Variant
      Set myDB = CreateScriptService("Database", "/home/user/Databases/Employees.odb")
      ' Tel kor mange tilsette i tabellen
      MsgBox myDB.DCount("[ID]", "EmployeeData")
      ' Returnerer summen av alle lønningane i tabellen
      MsgBox myDB.DSum("[Salary]", "EmployeeData")
      ' Nedanfor vert det vist nokre eksempel på filtrering av tabellar
      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%'")
    
I 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

Reknar ut eit SQL-uttrykk på ein enkelt post som vert returnert av ein WHERE-setning definert av parameteren Kriterium.

Viss spørjinga returnerer fleire postar, vert berre den første rekna med. Bruk parameterenOrderClause til å bestemma korleis spørjingsresultata skal sorterast.

Syntaks:

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

Parametrar:

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.

Eksempel:

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

Lagrar innhaldet i ein tabell eller resultatet av ei SELECT-spørjing eller av eit SQL-uttrykk i ei todimensjonal matrise. Den første indeksen i matrisa svarar til radene og den andre indeksen til kolonnane.

Du kan setja ei øvre grense for kor mange rader som skal returnerast. Kolonnenamn kan eventuelt setjast inn i den første rada i matrisa.

Den returnerte matrisa vil vera tom viss det ikkje vert returnert rader og det ikkje krevst kolonneoverskrifter.

Syntaks:

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

Parametrar:

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.

Eksempel:

Nedføre er det nokre eksempel på korleis metoden GetRows kan brukast:

I Basic

      Dim queryResults as Variant
      ' Returnerer alle radene i tabellen med kolonneoverskrifter
      queryResults = myDB.GetRows("EmployeeData", Header := True)
      ' Returnerer dei første 50 tilsettepostane sortert etter feltet «Fornamn»
      queryResults = myDB.GetRows("SELECT * FROM EmployeeData ORDER BY [FirstName]", MaxRows := 50)
    
I Python

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

RunSql

Utfører ei handlingsspørjing for ei SQL-setning, for eksempel oppretting av ein tabell, i tillegg til å setja inn, oppdatera og sletta postar.

Metoden returnerer Sann når han lukkast.

tip

Metoden RunSql vert avvist med ei feilmelding dersom databasen tidlegare vart opna som skriveverna.


Syntaks:

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

Parametrar:

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.

Eksempel:

I Basic

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

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

Alle ScriptForge Basic-rutinane og -identifikatorane som vert innleidde med understrek «_» er reserverte for internt bruk. Dei er ikkje meint brukte i Basic-makroar.