Database Manual · Chapter 1

Database Tutorial Start

QMachineStudio 4.0 handles SQLite and MSSQL databases directly from scripts with DB["connection name"], and manages connections, table structures and event functions on the database screens of the Solution Explorer.

This tutorial walks you end to end through the SampleProject\Database\DB_Sqlite project installed with QMachineStudio, learning the database features as you go. The sample runs on a single SQLite connection and is a small tool that registers, edits and deletes order processing history (order_history table) from the screen. The code in each chapter is taken from this project's RunScript\*.xms files (some excerpts are shortened).

Sample Project Layout

xscript
SampleProject/Database/DB_Sqlite/
├── DB_Sqlite.xmp                  # Project file
├── XDatabase/
│   ├── connections.json           # DB connection settings (read and saved by the Database Connections screen)
│   └── LocalDB.db                 # SQLite file (contains the order_history · measure_record tables)
└── RunScript/
    ├── Data.xms                   # DB_* functions (Open / Refresh / Insert / Update / Delete / ...)
    ├── ViewRun.xms                # Button handlers (OnOpenClick / OnAddClick / ...)
    ├── ModifyDlg.xms              # Record-edit dialog
    ├── Event.xms                  # Common event functions + DB event OnDbOpened
    └── (others: Init / Mon / Work / ViewMain)

Running the Sample

  1. Open DB_Sqlite.xmp with File → Open Project.
  2. Switch to the machine screen with Build → Run (F5); the run page ViewRun appears.
  3. Press Open to open the DB, then add, edit and delete rows with the other buttons.

Screen Layout — ViewRun

The run page (ViewRun) consists of 6 buttons, 1 DataGrid and 1 DataLabel that shows the connection state.

ButtonFunctionAction
OpenData::DB_Open()Connect + insert 5 sample rows if empty + refresh the DataGrid
AddData::DB_InsertSample()INSERT one new order
UpdateData::DB_UpdateSelected()Mark the selected row as done (end_time / result)
Modify...Data::DB_OpenModifyDlg()Open a dialog for free editing, UPDATE on OK
DeleteData::DB_DeleteSelected()DELETE the selected row
CloseData::DB_Close()Close the connection + clear the DataGrid

The DataLabel at the top displays Data::DbStatusText and shows the current connection state (● OPEN / ● CLOSED).

The Key — DB["connection name"]

In scripts, every database is accessed by connection name. The sample has a single connection named local.

xscript
// Open the connection
DB["local"].Open();
 
// SELECT, then read with RowCount / GetRowArray
DB["local"].RunSqlSelect("SELECT id, order_no, menu_name FROM order_history ORDER BY id ASC");
int rows = DB["local"].RowCount;
 
// Single value
int total = DB["local"].RunSqlScalarInt("SELECT COUNT(*) FROM order_history");
 
// Parameter binding ( array values fill the ? placeholders in order )
array p[] = {""};
p.Clear();
p.Add("O1234");
p.Add("Latte");
p.Add(SYS.DateTimeString);
string sql = "INSERT INTO order_history(order_no, menu_name, start_time) VALUES(?,?,?)";
 
// Transaction — Rollback on failure
DB["local"].BeginTransaction();
if( DB["local"].RunSqlQueryParam(sql, p) == false )
{
   DB["local"].Rollback();
}
else
{
   DB["local"].Commit();
}
 
// Close the connection
DB["local"].Close();

It follows the same name-indexed convention as IO["..."] and MOTOR["..."], so it feels familiar from the start. In the editor, typing DB[ lists the connection names and typing DB["local"]. lists the members through auto-completion.

The Three Database Screens

The Database group of the Solution Explorer has three screens.

ScreenWhat it doesChapter
Database ConnectionsRegister connections · test connections · set the journal mode2
Database StudioEdit table structure (Structure) · view data (Data) · run SQL (SQL) · backup3 · 4 · 9
Database EventsCheck which of the 8 DB event functions are implemented · add function stubs8

Learning Path

ChapterTopicSample code · screen
2Connection settings — the Database Connections screen and connections.jsonXDatabase\connections.json
3Table schema — order_history and structure templatesStructure tab · DB_InsertInitialSamples
4Validating with the SQL · Data tabs of Database Studio—
5INSERT · UPDATE · DELETE — parameter binding and transactionsDB_InsertSample · DB_UpdateSelected · DB_DeleteSelected
6SELECT — cached (RunSqlSelect) · cursor · single valueDB_Refresh
7DataGrid · ModifyDlg bindingsDispData · SelectIndex · Edit*
8Events — ViewRun button handlers and DB event functionsOnOpenClick and 5 more · OnDbOpened
9Backup · journal mode · operational checkpointsBackup · StartBackupThread

We recommend running the sample alongside the chapters and checking the results yourself.

Subscribe