Python API to Talk to a Zim Database

🔌 ZimAPI Developer Guide (Python Edition)

🚀 What Is ZimAPI?

ZimAPI is a Python interface that connects directly to the ZIM database engine. It allows developers to execute ZIM and SQL commands, manage transactions, transfer files, and interact with persistent data sets—all from Python.

But ZimAPI is more than just a connector. It’s a gateway to ZIM’s integrated database, which offers a unique and developer-friendly feature: automatic data set creation and session-based persistence.


🧠 Why ZIM Is Different

Unlike traditional SQL databases like MySQL or PostgreSQL, ZIM automatically creates a data set every time a query is executed. These data sets behave like dynamic views and remain available for the entire session—no need to define or manage them manually.

In other systems, a Python developer must explicitly request a view or cache query results. In ZIM, this happens automatically:

 

FIND 5 Customers -> sCustomers

 

This creates a set named sCustomers containing up to 5 customer records. You can interact with this set throughout the session:

 

DELETE 1 FROM sCustomers

 

Once the API session ends, ZIM automatically drops the data set. When a new session begins, a fresh set is created based on the new query context.


🛠️ Installation

After completing the full ZIM installation:

  1. Locate zimapi.py in your ZIM installation directory.
  2. Copy it to the directory where your Python scripts will run.

Tip: Keep zimapi.py in a shared utilities folder if you’re working across multiple projects.


🔗 Connecting to ZIM

Basic Setup

 

import zimapi
import os

zim = zimapi.Zimapi()
zim = zim.connect(
    dbname="your_database_name",
    host="localhost",       # Optional
    port=6002,              # Optional
    user="ZIM",             # Optional
    password=""             # Optional
)

print(zim.state)
zim.close()

 

Inline Connection

 

zim = zimapi.Zimapi(
    dbname="your_database_name",
    host="localhost",
    port=6002,
    user="ZIM",
    password=""
)
print(zim.state)
zim.close()

 

Note:

  • dbname is required.
  • host defaults to "localhost"
  • port defaults to 6002 (must match zimconfig.srv if changed)

🧩 Core Methods

zim.execute(command)

Executes a ZIM or SQL command.

 

if zim.execute("DELETE 1 Customers WHERE CustCode = 1") == 0:
    print("Executed successfully.")
elseif zim.state == 1001:
    print("Record not found.")
else:
    print("Error executing statement. Error Code =", zim.state)
endif

 


zim.transaction(), zim.commit(), zim.rollback()

Control explicit transactions for atomic operations.

 

zim.transaction()
zim.execute("UPDATE Customers SET Status = 'Active' WHERE CustCode = 1")
zim.commit()

 

Or roll back if needed:

 

zim.rollback()

 


zim.callproc(procedure_name, arguments)

Call a ZIM procedure with input/output parameters.

 

args = ("12", 7, "?", "?")
res = zim.callproc("MyProc", args)

if res[1] and res[2]:
    print("Result:", res[1], res[2])
else:
    print("Procedure returned no output.")
endif

 


zim.putfile(source, destination, format)

Upload a file from your local machine to the server.

 

zim.putfile("local.txt", "/server/data.txt", "/A")  # Text file

 


zim.getfile(source, destination, format)

Download a file from the server to your local machine.

 

zim.getfile("/server/data.txt", "local_copy.txt", "/A")  # Text file

 


🧵 Cursors & Sets: ZIM’s Secret Weapon

ZIM’s automatic data sets are one of its most powerful features. These sets persist for the duration of the session and behave like dynamic views.

Create and Use a Cursor

 

cur = zim.cursor("FIND 5 Customers")

while cur.rowcount() > 0:
    row = cur.fetchone()
    print(row)
endwhile

 

Or:

 

cur = zim.cursor()
cur.execute("FIND 5 Customers")

 


Cursor Utilities

MethodDescription
cur.close()Closes the cursor.
cur.rowcount()Number of rows available.
cur.fetchone()Fetches the next row.
cur.rownumber()Current row number.
cur.getname(index)Field name by index.
cur.describe(name)Field metadata.
cur.scroll(amount)Scrolls cursor by rows or to "TOP" / "BOTTOM"

📦 Sets: Persistent Views of Data

Sets are logical collections of rows that persist across the session. They behave like views and can be reused across multiple operations.

Create a Set

 

cur = zim.cursor("FIND 5 Customers -> sCustomers")

 

Manipulate the Set

 

zim.execute("DELETE 1 FROM sCustomers")

 

Use sets to:

  • Cache filtered data
  • Perform batch operations
  • Share views across procedures

🧪 Real-World Use Cases

🔄 1. Transactional Integrity

Wrap multiple operations in a transaction to ensure atomicity.

📞 2. Business Logic via Procedures

Trigger backend logic stored in ZIM procedures—like calculating discounts or validating credentials.

📁 3. Secure File Sync

Automate secure file transfers between client and server for compliance logs or audit trails.

📊 4. Dashboard Integration

Pull live data from ZIM into a Python-based dashboard using cursors and sets.


🧭 Summary

ZimAPI for Python is a powerful and developer-friendly interface that brings ZIM’s integrated database and automatic data set creation into your Python applications. It simplifies data access, enhances performance, and reduces boilerplate code—making it ideal for enterprise automation, smart dashboards, and intelligent safety systems.

Whether you’re modernizing legacy infrastructure or building new solutions, ZimAPI gives you the tools to do it efficiently and elegantly.

C-Sharp API to talk to a Zim Database

🔌 ZimAPI Developer Guide (C# Edition)

🚀 What Is ZimAPI?

ZimAPI for C# is a powerful interface that connects your .NET applications directly to the ZIM database engine. It enables developers to execute ZIM and SQL commands, manage transactions, transfer files, and interact with persistent data sets—all within a C# environment.

But ZimAPI is more than just a connector. It’s a gateway to ZIM’s integrated database, which offers a unique and developer-friendly feature: automatic data set creation and session-based persistence.


🧠 Why ZIM Is Different

Unlike traditional SQL databases like MySQL or PostgreSQL, ZIM automatically creates a data set every time a query is executed. These data sets behave like dynamic views and remain available for the entire session—no need to define or manage them manually.

In other systems, a developer must explicitly request a view or cache query results. In ZIM, this happens automatically:

 

FIND 5 Customers -> sCustomers

 

This creates a set named sCustomers containing up to 5 customer records. You can interact with this set throughout the session:

 

DELETE 1 FROM sCustomers

 

Once the API session ends, ZIM automatically drops the data set. When a new session begins, a fresh set is created based on the new query context.


🛠️ Installation

After completing the full ZIM installation:

  1. Locate zimapi.cs in your ZIM installation directory.
  2. Copy it to the directory where your C# application will be developed.
  3. Reference the compiled ZimAPI.dll in your project.

🌐 Globals

ZimAPI provides several global constants for convenience:

ConstantDescription
TOPIndicates the first record in a set
BOTTOMIndicates the last record in a set
UTF8Indicates a UTF-8 encoded ZIM database
ANSIIndicates an ANSI encoded ZIM database
NO_ERRORIndicates no error occurred

🔗 Connecting to ZIM

Basic Setup

 

using ZimConnection;

ZimAPI Conn = new ZimAPI();
Conn.Connect("DatabaseName", "localhost", 6002, "ZIM", "");
System.Console.WriteLine(Conn.State);
Conn.Close();

 

Inline Constructor

 

using ZimConnection;

ZimAPI Conn = new ZimAPI("DatabaseName", "localhost", 6002, "ZIM", "");
System.Console.WriteLine(Conn.State);
Conn.Close();

 

Note:

  • DatabaseName is required.
  • HostName defaults to "localhost"
  • PortNumber defaults to 6002 (must match zimconfig.srv if changed)
  • UserName defaults to "ZIM"
  • Password defaults to ""

🧩 Core Methods

Conn.Execute(command)

Executes a ZIM or SQL command.

 

if Conn.Execute("DELETE 1 Customers WHERE CustCode = 1") == 0
    System.Console("Executed successfully.")
elseif Conn.State = 1001
    System.Console("Record not found.")
else
    System.Console("Error executing statement. Error Code is = " + Conn.State + ".")
endif

 

Conn.Transaction(), Conn.Commit(), Conn.Rollback()

Control explicit transactions for atomic operations.

 

Conn.Transaction();
Conn.Execute("UPDATE Customers SET Status = 'Active' WHERE CustCode = 1");
Conn.Commit();

 

Or roll back if needed:

 

Conn.Rollback();

 

Conn.Callproc(procedure)

Call a ZIM procedure with input/output parameters.

 

string[] Result = Conn.Callproc("MyProc(\"12\", 7, \"?\", \"?\")");

if Result[1] != null and Result[2] != null
    System.Console("Result: " + Result[1] + ", " + Result[2])
else
    System.Console("Procedure returned no output.")
endif

 

Conn.Putfile() / Conn.Getfile()

Transfer files between client and server.

 

Conn.Putfile("local.txt", "/server/data.txt", "/A");  // Upload text file
Conn.Getfile("/server/data.txt", "local_copy.txt", "/A");  // Download it back

 

Conn.ErrorMessage() / Conn.ErrorCode()

Retrieve the last error message or code.

 

System.Console("Error: " + Conn.ErrorMessage());
System.Console("Code: " + Conn.ErrorCode());

 


🧵 Cursors & Sets: ZIM’s Secret Weapon

ZIM’s automatic data sets are one of its most powerful features. These sets persist for the duration of the session and behave like dynamic views.

Create and Use a Cursor

 

ZimAPI.ZimCursor MyCursor = Conn.Cursor("FIND 5 Customers");

while MyCursor.RowCount() > 0
    string row = MyCursor.FetchOne();
    System.Console(row);
endwhile

 

Or:

 

ZimAPI.ZimCursor MyCursor = Conn.Cursor();
MyCursor.Execute("FIND 5 Customers");

 

Cursor Utilities

MethodDescription
MyCursor.Close()Closes the cursor.
MyCursor.RowCount()Number of rows available.
MyCursor.FetchOne()Fetches the next row.
MyCursor.RowNumber()Current row number.
MyCursor.ValueOf(name)Gets field value by name.
MyCursor.ValueOf(index)Gets field value by index.
MyCursor.GetName(index)Gets field name by index.
MyCursor.FieldCount()Number of fields in the record.
MyCursor.Scroll(amount)Scrolls cursor by rows or to TOP / BOTTOM.

📦 Sets: Persistent Views of Data

Sets are logical collections of rows that persist across the session. They behave like views and can be reused across multiple operations.

Create a Set

 

ZimAPI.ZimCursor MyCursor = Conn.Cursor("FIND 5 Customers -> sCustomers");

 

Manipulate the Set

 

MyCursor.Execute("DELETE 1 FROM sCustomers");

 

Use sets to:

  • Cache filtered data
  • Perform batch operations
  • Share views across procedures

🧪 Real-World Use Cases

1. Smart Form Logic

Use ZimAPI to dynamically change UI elements based on backend data.

🔄 2. Transactional Integrity

Wrap multiple operations in a transaction to ensure atomicity.

📞 3. Business Logic via Procedures

Trigger backend logic stored in ZIM procedures—like calculating discounts or validating credentials.

📁 4. Secure File Sync

Automate secure file transfers between client and server for compliance logs or audit trails.

📊 5. Dashboard Integration

Pull live data from ZIM into a C#-based dashboard using cursors and sets.


🧭 Summary

ZimAPI for C# is a powerful and developer-friendly interface that brings ZIM’s integrated database and automatic data set creation into your .NET applications. It simplifies data access, enhances performance, and reduces boilerplate code—making it ideal for enterprise automation, smart dashboards, and intelligent safety systems.

Whether you’re modernizing legacy infrastructure or building new solutions, ZimAPI gives you the tools to do it efficiently and elegantly.

Python Connection

#pip3 -> python 3.9
# - Instalar com pip3
#pip3 install JayDeBeApi --user
#pip3 install JPype1==0.6.3 --user

import jaydebeapi

#variables to connect to zimjdbc8.jar


jclassname='zim.jdbc.ZJ_Driver'
jdbc_driver_loc = r'C:\Users\xxx\Documents\p01\zimjdbc8.jar'
jdbc_driver_name = 'zim.jdbc.ZJ_Driver'
host='localhost:6002'
#url and login variables
url='jdbc:zim://' + host + '/zimdb01'
login="ZIM"
psw=""

#sql to be executed at the Zim's side.
sql = "SELECT codie, name from test"

#connection to the JDBC driver
conn = jaydebeapi.connect(jclassname=jdbc_driver_name,
url=url, 
driver_args=[login, psw],
jars=jdbc_driver_loc)
#open the cursor
cur = conn.cursor()
#execute the SQL statement
cur.execute(sql)
#print the result 
print(cur.fetchall())...

Logging in to a Database

The driver provides a login dialog under one of two conditions. The login appears if

  • the application using the driver passes it a blank user id or password

  • the user id or password variables are not defined in the registry

The User ID and Password passed to the driver from the application override those defined in the registry.

Using Per User Entity Sets

Even though per user entity sets are private and only seen by the user that created them, they can still be available to an ODBC Driver connection by means of the Dynamic Creation of a Data Source, which informs the work path that contains the per user entity sets. When the third party software connects to the corresponding Zim database, the per user entity sets are handled in the proper way as though they were local to this connection.

In order for the ODBC Driver connection to properly “see” the data in the per user entity sets, the third party software must be invoked within the Zim session that created the per user entity sets and their corresponding data.

Invalid results will be achieved if the ODBC Driver connection is established:

. before starting the Zim session that will create the data and the proper connection;

. before creating the data, but within the Zim session;

. after ending the Zim session that created the data and the connection.

 

ODBC Driver

Zim supports Microsoft Open Database Connectivity Drivers (ODBC, defined by Microsoft as a standard way for applications to access data stored in database files) which allows third-party tools to access a Zim database via the Zim ODBC Driver.

This driver is used to access data from a Zim database that is either local to the machine on which the driver is installed or remotely located. In either case, Zim Server must be running in the machine where the database is located.

The way ZIM ODBC Driver works is this:

1) The third-party tool requires an external data connection using a Data Source (see Configuring a Data Source). This connection is performed by means of the Zim ODBC Driver;

2) Using the parameters provided by the Data Source, Zim ODBC Driver connects to Zim Server that is running in the specified machine;

3) Once the connection is established, the Zim Data Dictionary (Entity Sets and Relationships with fields) present in the Zim database is sent to the third-party tool for further operations.

Following to the connection, all operations go through these steps:

1) The third-party tool builds an SQL statement to perform the operation and sends this SQL statement to the Zim ODBC Driver;

2) The Zim ODBC Driver adapts the SQL statement to Zim needs and sends it to Zim Server;

3) Zim Server processes the statement and sends back the appropriate information;

4) This information is sent back to the third-party tool for processing.

The SQL statement provided by the third-party tool is described in Supported SQL Grammar. In particular, the SQL CREATE and SQL DROP commands are not supported for tables or indexes.

 

Supported SQL Grammar

Note: In Zim, constant strings can be represented either surrounded in single quotes (‘) or double quotes (“). In SQL, constant strings are surrounded by single quotes (‘) whereas identifiers are surrounded by double quotes (“).

statement ::= SELECT select | INSERT insert | DELETE delete | UPDATE update | passthroughSQL

passthroughSQL ::= any statement supported by the back end

tablename ::= identifier

columnname ::= identifier

select ::= selectcols FROM tablelist where groupby having orderby

delete ::= FROM table where

insert ::= INTO table insertvals

update ::= table SET setlist where

setlist ::= set | setlist , set

set ::= column = NULL | column = expression

insertvals ::= ( columnlist ) VALUES ( valuelist ) | VALUES ( valuelist )

columnlist ::= column , columnlist | column

column ::= columnname

valuelist ::= NULL , valuelist | expression , valuelist | expression | NULL

selectcols ::= selectallcols * | selectallcols selectlist

selectallcols ::= | ALL | DISTINCT

selectlist ::= expression , selectlist | expression

where ::= | WHERE boolean

having ::= | HAVING boolean

boolean ::= and | and OR boolean

and ::= not | not AND and

not ::= comparison | NOT comparison

comparison ::= ( boolean ) colref IS NULL | colref IS NOT NULL |

expression LIKE pattern | expression NOT LIKE pattern |

expression IN ( valuelist ) | expression NOT IN ( valuelist ) |

expression op expression

op ::= > | >= | < | <= | = | <>

pattern ::= string | ? | USER

expression ::= expression + times | expression – times | times

times ::= times * neg | times / neg | neg

neg ::= term | + term | – term

term ::= ( expression ) | colref | simpleterm | aggterm

aggterm ::= COUNT ( * ) | AVG ( expression ) | MAX ( expression ) | MIN ( expression ) | SUM ( expression )

simpleterm ::= string | realnumber | ? | USER | date | time | timestamp

groupby ::= | GROUP BY groupbyterms

groupbyterms ::= colref | colref , groupbyterms

orderby ::= | ORDER BY orderbyterms

orderbyterms ::= orderbyterm | orderbyterm , orderbyterms

orderbyterm ::= colref asc | integer asc

asc ::= | ASC | DESC

colref ::= aliasname.columnname | columnname

aliasname ::= identifier

tablelist ::= tableref, tablelist | tableref

tableref ::= table | table aliasname

table ::= tablename

identifier ::= an identifier (identifiers containing spaces must be enclosed in double quotation marks)

string ::= a string (enclosed in single quotation marks)

realnumber ::= a non-negative real number

integer ::= a non-negative integer

date ::= a date in ODBC escape clause format (for example, {d’1996-02-05′} or

   –(*vendor(Microsoft),product(ODBC) d’1996-02-05’*)–

time ::= a time in ODBC escape clause format (for example, {t’10:19:48′} or

   –(*vendor(Microsoft),product(ODBC) t ’10:19:48’*)–

timestamp ::= a timestamp in ODBC escape clause format (for example,

  {ts’1996-02-05 10:19:48.529′} or

  –(*vendor(Microsoft),product(ODBC) ts ‘1996-02-05 10:19:48.529″*)–

Configuring a Data Source

An ODBC Data Source to access a Zim database can be configured in two different ways:

. Using the Zim ODBC Driver Setup to create a data source;

. Using Zim language to dynamically create and maintain a data source tailored for specific needs like calling a third party software from within Zim.

In both cases, the Zim ODBC Driver product must have been previously installed in the machine where the setup or the dynamic configuration is going to happen.

Zim ODBC Driver Setup

The setup of the desired Data Source will happen via the Zim ODBC Driver setup dialog invoked this way (this procedure was based on Windows XP environments; other Windows environments might be slightly different):

. Press the Start button on windows;

. Select Control Panel;

. Select Administrative Tools;

. Select Data Sources (ODBC);

. On the ODBC Data Source Administrator window, either click on the User DSN or System DSN tab. The User DSN indicates that the new data source will be accessible by the current user of this Windows environment, whereas the System DSN indicates that the new data source can be used by all users of this machine provided that they have the appropriate permission. Unless internal policies used in your company state otherwise, click on the System DSN tab;

. Next, click on the “Add…” button the start the new setup (if you already have an existing Data Source that needs to be changed, click on the button “Configure…“);

. The Zim ODBC Driver Setup appears with the following aspect:

where the fields mean:

Data SourceProvides a unique name that identifies this Data Source. It can be any text to describe this particular set of connect parameters.
DB NameThe database name used to connect to Zim Server.
User IDAssigns the user name under which you wish to log in to the Zim database. This User ID must be known by the Zim database.
PasswordAssigns the password for “User ID”.
HostThe name or IP address of the machine where the target Zim Server is running.
Port NumberThe number of the port on which the Zim Server is listening.

Dynamic Creation of a Data Source

Zim language can be used to dynamically create and maintain a data source belonging to the System DSN group of data sources.

The following Zim statements create a new Data Source called “MyDataSource”:

let v = $setproperty(“REG:[ODBC]”, “MyDataSource”, $getproperty(“REG:[ODBC]”, “VERSION”))
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\DBQ”, “Example”)
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\Driver”, $getproperty(“REG:[ODBC]”, “DRIVER”))
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\DSN_NAME”, “MyDataSource”)
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\Host”, “localhost”)
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\Server”, “6002”)
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\UID”, “ZIM”)
let v = $setproperty(“REG:[ODBC]”, “MyDataSource\WorkPath”, $workpath)

After these Zim commands have been executed, any third party software that connects to a Zim database in order to retrieve or update data, can make use of the ODBC Data Source “MyDataSource” via a Zim SYSTEM command:

SYSTEM “C:\MySoftware\MyExecutable.exe MyDataSource” CLOSE

The properties “VERSION” and “DRIVER” cannot be set because the are established at installation time by the Zim ODBC Driver Installer.

A third party software can invoke a Data Source created this way and use per user entity sets. Refer to the section Using Per User Entity Sets for further details.

The same way data source properties can be set, they can also be retrieved using the Zim command $SetProperty as shown in these examples:

out $getproperty(“REG:[ODBC]”, “MyDataSource\DBQ”)                              % Prints the name of the database
out $getproperty(“REG:[ODBC]”, “MyDataSource\Host”)                              % Prints the address of the host

 

 

pt_BRPortuguese