SELECT Patterns
Reading SQL comes in three forms.
| Pattern | API | Use |
|---|---|---|
| A) Single value | RunSqlScalarInt(sql) and others | One-cell results such as COUNT(*) |
| B) Bulk SELECT | RunSqlSelect(sql) + RowCount + GetRowArray(i) / GetValue(i, col) | Filling a DataGrid, multi-row processing — the whole result is kept in memory |
| C) Cursor | SelectBegin(sql) + SelectNext() + GetString(col) … + SelectEnd() | Reading a large result row by row |
The sample project uses A and B.
Pattern A — Single Value
The empty-table check in DB_Open() is the typical example.
int rowCnt = DB["local"].RunSqlScalarInt("SELECT COUNT(*) FROM order_history");
if( rowCnt == 0 )
{
DB_InsertInitialSamples();
}Functions by type:
| Function | Return type |
|---|---|
RunSqlScalarInt(sql) | int |
RunSqlScalarDouble(sql) | double |
RunSqlScalar(sql) | string |
If the result is empty or cannot be converted to a number, 0 / 0.0 / "" is returned. The same values are returned when the SQL fails,
so when you must tell 0 apart from a failure, run it with RunSqlSelect and check the return value (bool).
Pattern B — Bulk SELECT (DB_Refresh)
DB_Refresh() in the sample shows the standard flow.
FUNCTION DB_Refresh()
{
if( DB["local"].IsOpen == false )
{
LogError($"DB_Refresh : DB is not open");
return false;
}
string sql = "SELECT id, order_no, menu_name, start_time, end_time, weight_g, result, is_error FROM order_history ORDER BY id ASC";
if( DB["local"].RunSqlSelect(sql) == false )
{
LogError($"DB_Refresh select failed : {DB["local"].LastError}");
ShowMessage(EB_Ok, $"DB Select failed : {DB["local"].LastError}");
return false;
}
DispData.Clear();
int rows = DB["local"].RowCount;
for( i, 0, rows-1 )
{
// GetRowArray : returns one row as an XArray in column order
// Join the XArray with commas into one CSV line that the DataGrid understands
array row = DB["local"].GetRowArray(/*row*/i);
string line = $"{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]}";
DispData.Add(line);
}
Log($"DB_Refresh : {rows} rows loaded");
return true;
}The 4-step Flow
RunSqlSelect(sql)— keeps the whole result in memory.falseon failure.RowCount— number of rows in the kept result (ColumnCountis the number of columns).GetRowArray(i)— returns rowi(from 0) as anarrayin column order.- Convert the result — here each row is joined into one CSV line and added to the
DispDataarray.
The kept result stays valid until the next RunSqlSelect runs or the connection closes. INSERT / UPDATE do not change it.
Cell-level Access
When you want to read cell by cell rather than row by row:
array p[] = {""};
p.Clear();
p.Add(3);
DB["local"].RunSqlSelectParam("SELECT id, menu_name, weight_g FROM order_history WHERE id=?", p);
int id = DB["local"].GetValueInt(/*row*/0, /*colName*/"id");
string menu = DB["local"].GetValue(/*row*/0, /*colName*/"menu_name");
double w = DB["local"].GetValueDouble(/*row*/0, /*colName*/"weight_g");DB_OpenModifyDlg in the sample (Chapter 7) copies every column of the selected row into the edit fields (Edit*) with
GetValue(SelectIndex, column name) from the result kept by DB_Refresh.
| Function | Meaning |
|---|---|
GetValue(row, col) | Cell value as a string ("" for NULL) |
GetValueInt(row, col) | Integer (0 if it cannot be converted) |
GetValueDouble(row, col) | Floating point (0.0 if it cannot be converted) |
IsNull(row, col) | Whether the cell is NULL |
GetColumnNames() | List of column names (array) |
GetColumnArray(col) · GetColumnArrayByIndex(i) | All values of one column (array) — by name or by index |
row is a 0-based row number and col is the column name (indexes are not accepted). To read a column by position,
use the elements of GetRowArray(row) or GetColumnArrayByIndex(i). Reading by name stays safe even if the column order changes.
The bulk SELECT method has no bool accessor. The sample stores booleans as INTEGER 0/1 (the is_error column),
so read with GetValueInt(row, col) and compare with == 1.
bool isError = ( DB["local"].GetValueInt(/*row*/0, /*colName*/"is_error") == 1 );Pattern C — Cursor (Large Results Row by Row)
Reads one row at a time without keeping the whole result in memory. This saves memory when there are many rows.
array p[] = {""};
p.Clear();
p.Add(3);
if( DB["local"].SelectBeginParam("SELECT id, menu_name, weight_g FROM order_history WHERE id >= ?", p) == false )
{
LogError($"SelectBegin failed : {DB["local"].LastError}");
return false;
}
while( DB["local"].SelectNext() )
{
int id = DB["local"].GetInt("id");
string menu = DB["local"].GetString("menu_name");
double w = DB["local"].GetDouble("weight_g");
Log($"id={id} menu={menu} weight={w}");
}
DB["local"].SelectEnd();- Start with
SelectBegin(sql)/SelectBeginParam(sql, p), and read the current row whileSelectNext()istrue(falsewhen no rows remain). - Read the current row with
GetString(col)·GetInt(col)·GetDouble(col)·GetBool(col). - Call
SelectEnd()when finished. Running other SQL on the same connection while the cursor is in use closes the cursor.
Common SELECT Forms
Based on the sample domain. Try them on the SQL tab (Chapter 4) first.
-- 1) Latest 50 rows (for DataGrid display)
SELECT id, order_no, menu_name, end_time, result
FROM order_history ORDER BY id DESC LIMIT 50;
-- 2) Count by result
SELECT result, COUNT(*) FROM order_history GROUP BY result;
-- 3) Errors only
SELECT id, order_no, menu_name FROM order_history WHERE is_error = 1;
-- 4) Time range — in scripts, pass a [from, to] array to RunSqlSelectParam
SELECT id, order_no FROM order_history
WHERE start_time >= ? AND start_time < ?;SELECT with Parameters
When you need parameter binding, use RunSqlSelectParam(sql, p) instead of RunSqlSelect(sql) —
the same pattern as RunSqlQueryParam for INSERT / UPDATE. RunSqlSelect is the single-argument version without parameters;
there is no overload that takes a second argument for SQL with ? placeholders.
array p[] = {""};
p.Clear();
p.Add(targetId);
DB["local"].RunSqlSelectParam("SELECT * FROM order_history WHERE id=?", p);
if( DB["local"].RowCount == 1 )
{
string menu = DB["local"].GetValue(0, "menu_name");
// ...
}Common Pitfalls
RowCountbelongs to the last SELECT — after INSERT / UPDATE, run SELECT again to get the correct row count. The sample solves this by callingDB_Refresh()at the end of every data-changing function.- Name the columns in SELECT — with
SELECT *the column order can change when the table structure changes, which is risky when reading by position withGetRowArray. - Empty results — when
RowCount == 0,GetValue(0, ...)returns an empty string, but the call is meaningless, so always guard it. LastErrorholds the message of the last failure — later successful commands do not clear it; it is cleared when the connection opens. Judge success by each function's return value, and useLastErrorto see the cause after a failure.
Next Chapter
With read and write code in place, it is time to show the data on screen — the next chapter covers the binding that refreshes the
DataGrid automatically when you change just the DispData array.