Database Manual · Chapter 5

INSERT · UPDATE · DELETE

We walk through the four functions in Data.xms that run data-changing SQL.

FunctionRolePattern
DB_InsertSampleINSERT one new orderParameter binding
DB_UpdateSelectedMark the selected row as doneTransaction + parameter binding
DB_DeleteSelectedDelete the selected rowParameter binding
DB_InsertInitialSamplesBulk INSERT 5 rows into an empty tableTransaction (multiple rows)

First, the two key ideas.

1) Parameter Binding — RunSqlQueryParam(sql, paramArray)

Instead of building SQL by string concatenation, pass the values as an array to the ? placeholders. This blocks SQL injection and removes small problems such as quote escaping.

xscript
array p[] = {""};
p.Clear();
p.Add(value1);
p.Add(value2);
// ... the number of ? must exactly equal the number of elements in p
 
string sql = "INSERT INTO ... VALUES(?, ?)";
DB["local"].RunSqlQueryParam(sql, p);
  • The array elements fill the ? placeholders in order. On an MSSQL connection you also write ?; it is converted to @p0, @p1 … internally.
  • All bound values are passed as strings. SQLite interprets them according to the column's type affinity. If you need an exact type, use CAST in the SQL.
  • On failure the call returns false and the cause is left in LastError.

2) Transactions — BeginTransaction / Commit / Rollback

Use them to run several SQL statements as one unit, or to undo every change when something fails. Always Rollback when something fails midway. While an unfinished transaction remains, the next BeginTransaction fails with transaction already started.

xscript
if( DB["local"].BeginTransaction() == false )
{
   return false;
}
 
if( DB["local"].RunSqlQueryParam(sql, p) == false )
{
   DB["local"].Rollback();
   return false;
}
 
if( DB["local"].Commit() == false )
{
   return false;
}

DB_InsertSample — Single-row INSERT

Called by the Add button. The menu cycles through 7 items, and the order number is incremented by the OrderSeq counter.

xscript
FUNCTION DB_InsertSample()
{
   if( DB["local"].IsOpen == false )
   {
      ShowMessage(EB_Ok, "DB is not open. Press [Open] first.");
      return false;
   }
 
   // Pick from the menu pool in turn (for learning — so the data does not look the same every time)
   array menuPool[] = {"Americano", "Latte", "Cappuccino", "Espresso", "Mocha", "Green Tea", "Lemonade"};
   OrderSeq = OrderSeq + 1;
   int menuIdx = OrderSeq % 7;
 
   array p[] = {""};
   p.Clear();
   p.Add($"O{OrderSeq}");          // order_no
   p.Add(menuPool[menuIdx]);       // menu_name
   p.Add(SYS.DateTimeString);      // start_time
   p.Add("");                      // end_time (empty while the job is in progress)
   p.Add(0);                       // weight_g
   p.Add("Pending");               // result
   p.Add(0);                       // is_error
 
   string sql = "INSERT INTO order_history(order_no, menu_name, start_time, end_time, weight_g, result, is_error) VALUES(?,?,?,?,?,?,?)";
   if( DB["local"].RunSqlQueryParam(sql, p) == false )
   {
      LogError($"DB_InsertSample failed : {DB["local"].LastError}");
      ShowMessage(EB_Ok, $"DB Insert failed : {DB["local"].LastError}");
      return false;
   }
 
   Log($"DB_InsertSample : O{OrderSeq} {menuPool[menuIdx]} inserted");
 
   return DB_Refresh();
}

Key points:

  • Always guard with IsOpen — a command sent to a closed connection fails and leaves db not open in LastError.
  • On failure, output to both LogError and ShowMessage — log (for tracing) + screen (for on-site notice).
  • At the end, call DB_Refresh() to refill the DataGrid (Chapter 6).

DB_UpdateSelected — Transactional UPDATE

Called by the Update button. It reads the PK of the row selected in the DataGrid and marks it as done (Done).

xscript
FUNCTION DB_UpdateSelected()
{
   if( DB["local"].IsOpen == false )
   {
      ShowMessage(EB_Ok, "DB is not open. Press [Open] first.");
      return false;
   }
 
   if( SelectIndex < 0 || SelectIndex >= DB["local"].RowCount )
   {
      ShowMessage(EB_Ok, "Select a row first.");
      return false;
   }
 
   // Read the PK (id) of the row selected in the DataGrid
   int targetId = DB["local"].GetValueInt(/*row*/SelectIndex, /*colName*/"id");
 
   // Start the transaction
   if( DB["local"].BeginTransaction() == false )
   {
      LogError($"BeginTransaction failed : {DB["local"].LastError}");
      ShowMessage(EB_Ok, $"DB Begin failed : {DB["local"].LastError}");
      return false;
   }
 
   array p[] = {""};
   p.Clear();
   p.Add(SYS.DateTimeString);   // end_time
   p.Add(250);                  // weight_g (fixed demo value)
   p.Add("Done");               // result
   p.Add(targetId);             // WHERE id = ?
 
   string sql = "UPDATE order_history SET end_time=?, weight_g=?, result=? WHERE id=?";
   if( DB["local"].RunSqlQueryParam(sql, p) == false )
   {
      DB["local"].Rollback();
      LogError($"DB_UpdateSelected failed : {DB["local"].LastError}");
      ShowMessage(EB_Ok, $"DB Update failed : {DB["local"].LastError}");
      return false;
   }
 
   if( DB["local"].Commit() == false )
   {
      LogError($"Commit failed : {DB["local"].LastError}");
      ShowMessage(EB_Ok, $"DB Commit failed : {DB["local"].LastError}");
      return false;
   }
 
   Log($"DB_UpdateSelected : id={targetId} updated");
 
   return DB_Refresh();
}

SelectIndex is the selected-row index of the DataGrid covered in Chapter 7. The DataGrid rows are in the same order as the result of the last SELECT (DB_Refresh), so GetValueInt(SelectIndex, "id") reads the PK of that row — the pattern of reading a cell by row number and column name.

DB_DeleteSelected — Simple DELETE

xscript
FUNCTION DB_DeleteSelected()
{
   // ( the IsOpen · SelectIndex guards are the same as in DB_UpdateSelected )
 
   int targetId = DB["local"].GetValueInt(/*row*/SelectIndex, /*colName*/"id");
 
   array p[] = {""};
   p.Clear();
   p.Add(targetId);
 
   string sql = "DELETE FROM order_history WHERE id=?";
   if( DB["local"].RunSqlQueryParam(sql, p) == false )
   {
      LogError($"DB_DeleteSelected failed : {DB["local"].LastError}");
      ShowMessage(EB_Ok, $"DB Delete failed : {DB["local"].LastError}");
      return false;
   }
 
   Log($"DB_DeleteSelected : id={targetId} deleted");
   SelectIndex = -1;
 
   return DB_Refresh();
}

Why reset SelectIndex = -1 — right after a delete, reusing the same index would point to a different row.

DB_InsertInitialSamples — Multiple Rows in One Transaction

Called only once, when an empty table is first opened. It bundles 5 rows into one transaction for both consistency and speed. The excerpt below keeps only the essentials.

xscript
array menuPool[]   = {"Americano",  "Latte",      "Cappuccino", "Espresso",  "Mocha"};
array weightPool[] = {250,          300,          280,          30,          320};
 
if( DB["local"].BeginTransaction() == false )
{
   return false;
}
 
string sql = "INSERT INTO order_history(order_no, menu_name, start_time, end_time, weight_g, result, is_error) VALUES(?,?,?,?,?,?,?)";
 
for( i, 0, 4 )
{
   OrderSeq = OrderSeq + 1;
 
   array p[] = {""};
   p.Clear();
   p.Add($"O{OrderSeq}");
   p.Add(menuPool[i]);
   // ... start_time · end_time · weight_g · result · is_error
 
   if( DB["local"].RunSqlQueryParam(sql, p) == false )
   {
      DB["local"].Rollback();
      return false;
   }
}
 
if( DB["local"].Commit() == false )
{
   return false;
}

With 5 rows the difference looks small, but in real production that loads hundreds to thousands of history rows at once, bundling them into one transaction is far faster, and a failure midway never leaves only part of the rows inserted.

Next Chapter

Reading (SELECT) remains — RunSqlSelect and GetRowArray, the single-value RunSqlScalarInt, and the cursor method.

Subscribe