PALATINELABSDocsENES

Pages

↑↓ to moveEnter to openEsc to close

Database package guide

Open database sessions, run parameterized statements, manage transactions, and import or export rows.

Version 2.17.1. Installed versions can differ. Examples are illustrative and not tested. See Packages.

Jump to actions

Prerequisites

The Device needs a driver for your database: SqlServer, Sqlite, Odbc or OleDb. An ODBC driver must be set up on the Device and match its 32-bit or 64-bit runtime. OLE DB needs Windows and the installed OLE DB driver.

DatabaseHow to connect
SQL Server, SQLite, Access (.mdb)connectionMode=USER⁠, then fill in the fields.
Other (MySQL, PostgreSQL, Oracle)connectionMode=DEFAULT with an ODBC or OLE DB connection string. USER refuses them.

Rules:

Sample setup

SQLite examples (session DbLab):

  1. Create the folder samples.
  2. Connect with session=DbLab, connectionMode=USER, databaseProvider=SqLite, sqliteFilePath=samples/guide.db.
  3. With Insert/Update/Delete, run CREATE TABLE people (id INTEGER, name TEXT).
  4. Run INSERT INTO people (id, name) VALUES (@id, @name) twice, with parameters id=1, name=Ada and id=2, name=Linus (id Number, name String).
  5. Create the Dictionary personParameters: name=Grace (String), id=3 (Number).

Stored procedure examples (session SqlLab):

  1. Connect with session=SqlLab, connectionMode=USER, databaseProvider=SQLOLEDB_1, server=database.example.com, database=AutomationSamples. Use your own test server. The Device's account must be allowed to sign in and run procedures.
  2. Create SampleEcho as shown in Manage stored procedure.
  3. Create the Table procedureParameters with these four String columns and two rows, in this order. A JSON object does not work. inOrOutParamter is spelled this way; do not correct it.
parameternameinOrOutParamterparametervalueoutputParamType
nameInputAdaVARCHAR
echoOutputVARCHAR

Shared fields

Many actions use these fields. Each action's Inputs part says which.

InputEditor fieldType; default; requirementUse
sessionSession nameStringdefault emptyrequired at runtimeThe connection name, for example DbLab⁠. Not empty. Connect creates it; other actions need it open. One transaction uses one session.
parametersParameters for untrusted valuesDictionarydefault emptyoptionalValues for the SQL markers, for example {"id":1} for WHERE id=@id⁠. ODBC and OLE DB fill ? in the order you added the values.
timeOutTimeout for the query in secondsNumberdefault 0optionalSeconds to wait for the SQL. 0 or less: the database default. Not the Connect timeout.
fetchSizeMaximum number of records to fetchNumberdefault 0optionalMost rows to read from the first result. 0 or less reads all.
doExportExport data to CSVBooleandefault falseoptionaltrue⁠: also write the rows to CSV. Run stored procedure also needs File Path, or writes nothing.
filePathFile PathStringdefault emptyoptionalThe CSV file, for example samples/people.csv⁠. Missing folders are created. CSV uses commas and quotes when needed. Replaced unless appendTo=true⁠.
encodingTypeEncodingEncodingTypedefault UTF8optionalANSI = Windows-1252. UNICODE = UTF-16. UTF8 = UTF-8.
appendToAppend to the existing fileBooleandefault falseoptionaltrue⁠: add to a file that has content. false⁠: replace it. Columns and encoding are not checked.
OutputTypeMeaning
resultTableRows with the database's column names, typed Number, Boolean, Datetime or String. NULL becomes empty text. In peopleRows⁠, $peopleRows[0].name$ is Ada⁠.

Other shared meanings:

Actions

Bulk insert (databaseBatchInsert)

Add many rows from a Table or a CSV file to a database table, one parameterized INSERT per row.

Inputs

InputEditor fieldType; default; requirementUse
csvFilePathSource fileStringdefault emptyoptionalA UTF-8 file, for example samples/people.csv⁠. Its first row gives the column names. Used only when Source table has no columns.
sourceTableSource tableTabledefault emptyoptionalA Table with columns wins over the file, even with zero rows. Example: $newPeople$⁠.
tableNameTable nameStringdefault emptyrequiredA table that exists, for example people⁠. Used as one name: dbo.people is not split. Its columns must accept the values as text.
delimiterDelimiterBulkDelimiterdefault commaoptionalFile only: comma⁠, tab⁠, newLine (one value per line) or other (Specific delimiter). Quotes work.
specificDelimiterSpecific delimiterStringdefault emptyoptionalRequired for other⁠, for example ; or ::⁠. Otherwise not used.
csvStartRowNumberStart row numberNumberdefault 2optionalFirst data row of the file. 2 skips the header. The header is skipped also below 2; above 2 skips more rows.
columnMappingsColumns mappingDictionarydefault emptyoptionalSource to table names, for example {"file_id":"id","file_name":"name"}⁠. Only listed columns are added. Empty: all columns, same names.
batchSizeBatch sizeNumberdefault 200optionalSave every N rows. 0 or less saves all at the end. If a later batch fails, earlier batches stay saved. Ignored inside Begin/End database transaction.
timeoutInSecondsTimeout (seconds)Numberdefault 3600optionalSeconds for each INSERT, not the whole import. 0 or less: the database default.

Also uses the shared fields: session.

Outputs

OutputTypeMeaning
insertedNumberThe sum of row counts from the database, only on success. Inside a transaction, the rows are not saved yet.

Example

After the sample setup, create the Table newPeople with String columns id, name and rows (7, Hopper), (8, Turing). Begin a transaction to test all or nothing. Set session=DbLab, sourceTable=$newPeople$, tableName=people, columnMappings={}, batchSize=200, timeoutInSeconds=30. Put inserted in Number insertCount. Commit only after you check it. For a file, leave Source table empty and set csvFilePath=samples/people.csv (header id,name, same rows), delimiter=comma, csvStartRowNumber=2.

Expected result

insertCount is 2. Outside a transaction, a failure undoes only the current batch. Inside one, nothing is saved or undone until you End it. Empty text becomes NULL. Columns with no rows give 0. It fails when no column matches, the file is missing or bad, or a value breaks a rule. Limit: 100,000 rows and 1,000,000 cells from a file.

Back to actions

Begin database transaction (databaseBegin)

Start a transaction. The session's next commands join it until End database transaction.

Inputs

Uses the shared fields: session.

Outputs

None.

Example

After the sample setup, set session=DbLab. Add row 3 with Insert/Update/Delete. End with option=Rollback.

Expected result

The transaction is open. After the rollback, row 3 is gone. If one is already open, the step fails. No nesting or savepoints.

Back to actions

End database transaction (databaseCommit)

Save or undo all commands since Begin.

Inputs

InputEditor fieldType; default; requirementUse
optionOptionEndTransactiondefault CommitoptionalCommit saves. Rollback undoes. Needs an open transaction, which ends even if this step fails.

Also uses the shared fields: session.

Outputs

None.

Example

In DbLab, Begin and add (3, Grace). Set session=DbLab, option=Rollback. To keep the row, use option=Commit.

Expected result

Rollback leaves two rows. Commit keeps row 3. With no open transaction, it fails. On a database error, the transaction still ends: check the data before you write more.

Back to actions

Connect (databaseConnect)

Open a database connection under a session name.

Inputs

InputEditor fieldType; default; requirementUse
connectionModeConnection modeConnectionModedefault DEFAULToptionalDEFAULT⁠: you write the connection string and pick the Driver. USER⁠: you fill in Database type and the server or file fields. The other mode's fields are ignored.
connectionOptionConnection stringConnectionOptiondefault textoptionalDEFAULT only. text⁠: use connectionURL⁠. credential⁠: use the password of connectionURLCV⁠.
connectionURLConnection stringStringdefault emptyoptionalFor DEFAULT with text⁠. SQLite example: Data Source=C:\AutomationSamples\guide.db⁠. Keep secrets in a Credential.
connectionURLCVConnection string credentialCredentialdefault emptyoptionalFor DEFAULT with credential⁠: the password holds the whole string; the user name is ignored. Never copy it into a String.
credentialEntryListDatabase connection parametersDictionarydefault emptyoptionalDEFAULT only. Text values added as key=value⁠, for example SQLite {"Mode":"ReadOnly"}⁠. Not escaped: follow the driver's rules.
driverDriverDriverdefault OdbcoptionalDEFAULT only: Odbc⁠, OleDb⁠, SqlServer or Sqlite⁠, to match the string.
use64BitDriverUse ODBC 64-bit driver for connectionBooleandefault falseoptionaleditor: use64BitDriver=trueNot used. Leave as is. Match the ODBC driver to the Device yourself.
databaseProviderDatabase typeDatabaseProviderdefault SQLOLEDB_1optionalUSER only. SQLOLEDB_1 = SQL Server. Microsoft_Jet_OLEDB_4_0 = Access (Jet OLE DB). SqLite = SQLite. MYSQL⁠, Postgre and Oracle fail.
serverEnter a server nameStringdefault emptyoptionalUSER SQL Server host, for example database.example.com⁠. Instance or Port is added.
databaseDatabase nameStringdefault emptyoptionalUSER SQL Server database, for example AutomationSamples⁠. Empty: the login's default.
userUser nameCredentialdefault emptyoptionalUSER SQL Server login name (the Credential's user name; its password is ignored). Empty: sign in as the Device's Windows account.
authPasswordCredentialdefault emptyoptionalThe SQL Server password, when User name is set (the Credential's password). It can be the same Credential as User name.
instanceInstance nameStringdefault emptyoptionalUSER SQL Server instance, for example SAMPLE⁠, added as server\SAMPLE⁠. Port is then ignored.
timeoutTimeout in secondsNumberdefault 0optionalUSER SQL Server: seconds to wait for the connection. 0 or less: the default. Not the query timeout.
portPortNumberdefault 0optionalUSER SQL Server port, for example 1433⁠, only with no Instance. 0 or less: no port.
dbFilePathDatabase file pathStringdefault emptyrequired in stated branchRequired for USER Access: the file, for example samples/guide.mdb⁠, readable and writable. The Jet OLE DB driver must be installed and match the 32-bit or 64-bit runtime.
sqliteFilePathDatabase file pathStringdefault emptyrequired in stated branchRequired for USER SQLite, for example samples/guide.db⁠. The folder must exist; a missing file is created.
oracleInstanceSelectOracle instanceOracleInstanceSelectdefault sidoptionaleditor: databaseProvider=Oraclesid⁠, serviceName or tns⁠. Not used: USER has no Oracle. Use a DEFAULT string.
isUserDefinedDriverUse specific databaseBooleandefault falseoptionalNot supported. Keep false⁠: true always fails.
filePathDriver fileStringdefault emptyoptionaleditor: isUserDefinedDriver=trueNot supported: custom driver files cannot load. Leave empty.

Also uses the shared fields: session.

Outputs

OutputTypeMeaning
sessionNameStringThe session name, for $dbSession$⁠. No password or connection string.

Example

Create the folder samples. Set session=DbLab, connectionMode=USER, databaseProvider=SqLite, sqliteFilePath=samples/guide.db, isUserDefinedDriver=false. Put sessionName in String dbSession. No sign-in is needed.

Expected result

dbSession is DbLab, and the SQLite file is open or created. It fails on an empty name, a missing driver, an unsupported type, wrong settings or no access. A failed connection is not kept.

Back to actions

Manage stored procedure (databaseCreateUpdateDelete)

Run a full command, usually CREATE, ALTER or DROP PROCEDURE. Any SQL runs, as far as the account allows.

Inputs

InputEditor fieldType; default; requirementUse
queryEnter full commandStringdefault emptyrequiredShared fields.

Also uses the shared fields: parameters, timeOut, session.

Outputs

OutputTypeMeaning
rowsAffectedNumberThe database's count. Commands that create or change objects often give -1⁠; check the object.

Example

In SqlLab, set session=SqlLab and timeOut=30. Leave Parameters empty and enter this command. Put rowsAffected in ddlCount. Do not test DROP on a real object.

CREATE PROCEDURE SampleEcho
  @name nvarchar(100), @echo nvarchar(100) OUTPUT
AS
BEGIN
  SET NOCOUNT ON;
  SET @echo = @name;
END

Expected result

SampleEcho exists for Run stored procedure. The count can be -1. It fails if the object exists. SQLite has no procedures, but this action can run other SQLite commands, such as creating a test view. Whether a rollback undoes such commands depends on the database.

Back to actions

Disconnect (databaseDisconnect)

Close one connection. An open transaction closes without saving.

Inputs

InputEditor fieldType; default; requirementUse
dosaveDataKeep database schema in cache until bot finishes runningBooleandefault falseoptionaleditor: dosaveData=trueNot used. Leave false⁠. Nothing is kept.

Also uses the shared fields: session.

Outputs

None.

Example

After the DbLab steps, set session=DbLab, dosaveData=false. To save an open transaction, End it with Commit first.

Expected result

The session is gone; changes not committed are lost. Later commands need a new Connect.

Back to actions

Export to data table (databaseExportToDataTable)

Read query rows into a Table. Same as Read from, without CSV.

Inputs

InputEditor fieldType; default; requirementUse
queryEnter SELECT StatementStringdefault emptyrequiredShared fields.

Also uses the shared fields: parameters, fetchSize, timeOut, session.

Outputs

result (Table): see shared fields.

Example

After the sample setup, set session=DbLab, query=SELECT id, name FROM people ORDER BY id, fetchSize=1 and timeOut=30. Leave Parameters empty. Put result in Table peopleRows.

Expected result

The Table has Number column id, String column name and one row (1, Ada). Rows count from 0. No match gives an empty Table with the columns.

Back to actions

Export to file stream (databaseExportToFileStream)

Write query or procedure rows to a CSV file, which is replaced. All rows are held in memory first.

Inputs

InputEditor fieldType; default; requirementUse
readFromDatabaseRead from databaseReadFromdefault selectStatementoptionalselectStatement⁠: SELECT statement and SELECT parameters. selectStoredProcedure⁠: Stored procedure name and the Parameters Table. The other fields are ignored.
selectStatementSELECT statementStringdefault emptyoptionalThe SQL, for example SELECT id, name FROM people ORDER BY id⁠. Outside values go in SELECT parameters.
storedProcedureNameStored procedure nameStringdefault emptyoptionalA procedure that exists, for example SampleEcho in SqlLab. SQLite has none.
parametersParametersTabledefault emptyoptionalShared fields.
queryParametersSELECT parameters for untrusted valuesDictionarydefault emptyoptionalSELECT values, for example {"id":1} with WHERE id=@id⁠. selectStatement only.
timeOutTimeout in secondsNumberdefault 0optionalShared fields.
fileNameFile nameStringdefault emptyrequiredThe CSV file, for example samples/people.csv⁠. Missing folders are created.
encodingEncodingEncodingTypedefault UTF8optionalAs encodingType in Shared fields.
includeHeadersInclude column headersBooleandefault falseoptionaltrue⁠: column names first. false⁠: data only.

Also uses the shared fields: session, fetchSize.

Outputs

OutputTypeMeaning
fileAnyThe CSV file with its full path. Use it where a file path is needed. Not an open file.

Example

After the sample setup, set session=DbLab, readFromDatabase=selectStatement, selectStatement=SELECT id, name FROM people ORDER BY id, queryParameters={}, fetchSize=0, timeOut=30, fileName=samples/people-export.csv, encoding=UTF8, includeHeaders=true. Put file in a File variable exportFile. For a procedure, use SqlLab, storedProcedureName=SampleEcho, parameters=$procedureParameters$; its first result can be empty.

Expected result

The file has id,name, 1,Ada and 2,Linus. exportFile has the full path. Zero rows still write the file, with headers if asked and known. A missing file name or no write permission fails. Procedure output values are not returned.

Back to actions

Insert/Update/Delete (databaseInsertUpdateDelete)

Run a command that changes data, or any other command, and get the changed-row count. Use a transaction for changes that belong together.

Inputs

InputEditor fieldType; default; requirementUse
queryStatementStringdefault emptyrequiredShared fields.

Also uses the shared fields: parameters, timeOut, session.

Outputs

OutputTypeMeaning
rowsAffectedNumberRows changed. Can be -1 for commands that change no rows. Not a success flag.

Example

After the sample setup, set session=DbLab, query=INSERT INTO people (id, name) VALUES (@id, @name), parameters=$personParameters$, timeOut=30. Put rowsAffected in Number changedRows.

Expected result

changedRows is 1, and id 3 is Grace. UPDATE or DELETE can give 0 when no row matches. A committed DELETE is permanent. A value that breaks a table rule fails.

Back to actions

Read from (databaseSqlQuery)

Read query rows into a Table, and optionally write them to CSV.

Read from returns a Table and can also export the same rows to CSV.
Read from returns the first result set as a Table. With doExport=true, it also writes those rows to CSV. A positive fetchSize limits rows. View full size

Inputs

InputEditor fieldType; default; requirementUse
queryEnter SELECT StatementStringdefault emptyrequiredShared fields.
withHeaderExport data with headerBooleandefault falseoptionaltrue⁠: column names first, but not again when adding to a file with content.
noBlankCSVDon't create file if no data is foundBooleandefault falseoptionaltrue⁠: zero rows write no file, and an old file stays. false⁠: an empty file can be written.

Also uses the shared fields: parameters, fetchSize, timeOut, doExport, filePath, encodingType, appendTo, session.

Outputs

result (Table): see shared fields.

Example

Use the Export to data table example, then also set doExport=true, filePath=samples/first-person.csv, encodingType=UTF8, withHeader=true, noBlankCSV=true, appendTo=false.

Expected result

The Table is the same as in Export to data table. The file is replaced and has id,name and 1,Ada. If the file cannot be written, the step fails after the query ran.

Back to actions

Run stored procedure (databaseStore)

Call a procedure and get its output values as a Dictionary. Its rows can go to CSV but are not in the output.

Inputs

InputEditor fieldType; default; requirementUse
queryProcedure nameStringdefault emptyrequiredShared fields.
entryListParametersTabledefault emptyoptionalShared fields.
withHeaderWith headerBooleandefault falseoptionaltrue⁠: column names first, but not again when adding to a file with content.

Also uses the shared fields: fetchSize, timeOut, doExport, filePath, encodingType, appendTo, session.

Outputs

OutputTypeMeaning
resultDictionaryThe output values by name, as text, read after the first result.

Example

Do the SqlLab sample setup. Set session=SqlLab, query=SampleEcho, entryList=$procedureParameters$, fetchSize=0, timeOut=30, doExport=false. Put result in Dictionary procedureOutputs.

Expected result

$procedureOutputs.echo$ is Ada. Only Output and InputOutput entries come back, by the name you gave. All values are text; NULL is empty text. No outputs give an empty Dictionary. With CSV export on, file access can also fail.

Back to actions