Database Support

DWScript provides a modern database abstraction layer through the System.Data unit. It supports multiple drivers, with SQLite being natively supported.

Connecting

Connecting to a database is simple using the DataBase.Create factory method.

uses System.Data;

var db := DataBase.Create('SQLite', [':memory:']);

Querying Data

Use Query for SELECT statements. It returns a DataSet that you can iterate through.

uses System.Data;
var db := DataBase.Create('SQLite', [':memory:']);
db.Exec('CREATE TABLE Users (ID INTEGER, Name TEXT, Active INTEGER)');
db.Exec('INSERT INTO Users VALUES (1, "Alice", 1)');

var ds := db.Query('SELECT ID, Name FROM Users WHERE Active = ?', [1]);

// ds.Step is the preferred way to iterate: it moves to the next record 
// and returns True as long as there is data to read.
while ds.Step do begin
  PrintLn(ds.AsString(1).ToHtml); // Access by 0-based index
end;
Result
Alice

Updating Data

Use Exec for commands that modify data (INSERT, UPDATE, DELETE). Always use parameterized queries to prevent SQL injection.

uses System.Data;
var db := DataBase.Create('SQLite', [':memory:']);
db.Exec('CREATE TABLE Users (ID INTEGER, Name TEXT)');

db.Exec('INSERT INTO Users (Name) VALUES (?)', ['Alice']);

JSON Integration

Datasets can be automatically converted to JSON strings, which is extremely useful for building REST APIs.

uses System.Data;
var db := DataBase.Create('SQLite', [':memory:']);
db.Exec('CREATE TABLE Users (ID INTEGER, Name TEXT)');
db.Exec('INSERT INTO Users VALUES (1, "Alice")');

var ds := db.Query('SELECT * FROM Users');
PrintLn(ds.StringifyAll);
Result
[{"ID":1,"Name":"Alice"}]

Related Reference

For a full list of database methods, transaction management, and specialized dataset helpers, see the reference documentation:

On this page