matlab-write-database
The matlab-write-database skill enables MATLAB users to write data to relational databases using sqlwrite for bulk inserts, sqlupdate for row modifications, execute for SQL statements, and databasePreparedStatement for parameterized queries. Use this skill when exporting MATLAB tables, updating database records, running stored procedures, managing transactions with commit/rollback, or performing any database write operation through the Database Toolbox.
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-write-database && cp -r /tmp/matlab-write-database/skills-catalog/reporting-and-database-access/matlab-write-database ~/.claude/skills/matlab-write-databaseSKILL.md
# MATLAB Database Export Architect
Use when writing data to relational databases, executing SQL statements, managing transactions, running stored procedures, or using SQL prepared statements. Covers all Database Toolbox operations that modify the database.
## When to Use This Skill
- Writing/inserting MATLAB data into a database table
- Updating existing rows in a database table
- Deleting data from a database
- Executing arbitrary SQL statements (DDL, DML)
- Running stored procedures or custom database functions
- Managing transactions (commit/rollback)
- Using SQL prepared statements for parameterized queries
- Creating or altering database table structures
- User mentions keywords: write, export, insert, sqlwrite, sqlupdate, update, delete, execute, stored procedure, runstoredprocedure, transaction, commit, rollback, DDL, CREATE TABLE, ALTER, prepared statement, bulk insert
## When NOT to Use
- Reading/importing data from a database — use `sqlread`/`fetch` with `RowFilter` and `databaseImportOptions`
- Object-oriented writes with class mapping — use ORM (`ormwrite`/`ormupdate` with `Mappable` classes)
- MongoDB, Cassandra, or Neo4j writes — these have their own document/graph-specific write interfaces
- Large data that doesn't fit in memory — use `DatabaseDatastore` + chunked processing for reads, or chunked `sqlwrite` loops for writes
## Critical Rules
### Credential Security
- **NEVER** hardcode passwords or credentials in generated code.
- **ALWAYS** use `setSecret` / `getSecret` (R2024a+) for credential storage.
### Database Connection
- **ALWAYS** establish and verify a connection before any export operation. Check `isopen(conn)` after connecting.
- **ALWAYS** close connections with `close(conn)` when done.
### Transaction Safety
- **ALWAYS** set `AutoCommit` to `off` when using `commit` / `rollback` for transaction control.
- **ALWAYS** wrap multi-statement operations in a transaction when atomicity is required.
- **ALWAYS** use `rollback` in error-handling blocks to undo partial changes on failure.
## Decision Framework
| Goal | Function | When to Use |
|------|----------|-------------|
| Write MATLAB table to DB table | `sqlwrite` | Bulk insert of tabular data; creates table if needed |
| Modify existing rows | `sqlupdate` | Update specific rows matching a filter (R2023a+) |
| Run DDL or raw SQL | `execute` | CREATE TABLE, DROP, ALTER, simple CALL statements |
| Repeated parameterized inserts | `databasePreparedStatement` | High-frequency inserts with varying values |
| Stored procedure with typed outputs | `runstoredprocedure` | Need typed output arguments from stored procedure (JDBC/ODBC only) |
| Simple stored procedure call | `execute` with CALL | No typed output args needed; result sets returned |
> **`execute` vs `runstoredprocedure`:** Use `runstoredprocedure` when you need typed output arguments. Use `execute` with CALL for simple invocation or when you only need result sets.
## Function Reference
| Function | Purpose | Since |
|----------|---------|-------|
| `sqlwrite` | Insert MATLAB table into database table | R2018a |
| `sqlupdate` | Update rows in database table matching a filter | R2023a |
| `update` | Replace data in database table (legacy) | R2006a |
| `execute` | Execute any SQL statement (DDL, DML, stored procs) | R2018b |
| `runstoredprocedure` | Call stored procedure with input/output arguments (JDBC/ODBC only) | R2006b |
| `commit` | Make database changes permanent | R2006a |
| `rollback` | Undo database changes | R2006a |
| `databasePreparedStatement` | Create SQL prepared statement (JDBC only) | R2019b |
| `bindParamValues` | Bind values to prepared statement parameters | R2019b |
### Edge Cases
- **NULL values:** MATLAB `missing`, `NaN`, or empty `""` map to SQL NULL in `sqlwrite`
- **Type mismatches:** Ensure MATLAB column types match DB column types (e.g., `int32` not `double` for INTEGER columns)
- **Auto-increment PKs:** Omit the auto-increment column from the MATLAB table before calling `sqlwrite`
## Core Concepts
See knowledge cards for detailed usage and examples:
- **Insert and update data**: `reference/cards/sqlwrite-sqlupdate.md`
- **Execute SQL and stored procedures**: `reference/cards/execute-storedproc.md`
- **Transaction management**: `reference/cards/transactions.md`
- **Prepared statements (JDBC only)**: `reference/cards/prepared-statements.md`
## Complete Examples
See knowledge cards for complete examples:
- **Insert computed results**: `reference/cards/sqlwrite-sqlupdate.md`
- **Atomic multi-table update with transaction**: `reference/cards/transactions.md`
- **Parameterized insert with prepared statement**: `reference/cards/prepared-statements.md`
### Common Mistakes
```matlab
% INCORRECT — inserting rows one at a time in a loop (very slow)
for i = 1:height(data)
sqlwrite(conn, "orders", data(i,:));
end
% CORRECT — batch insert the entire table at once
sqlwrite(conn, "orders", data);
% INCORRECT — no transaction control for multi-table writes
sqlwrite(conn, "orders", orderData);
sqlwrite(conn, "order_items", itemData); % if this fails, orders are orphaned
% CORRECT — use transaction control for atomic multi-table writes
conn.AutoCommit = 'off';
try
sqlwrite(conn, "orders", orderData);
sqlwrite(conn, "order_items", itemData);
commit(conn);
catch ME
rollback(conn);
conn.AutoCommit = 'on'; %#ok<NASGU> restore before rethrowing
rethrow(ME);
end
conn.AutoCommit = 'on';
% INCORRECT — including auto-increment column in sqlwrite
data = table(1, "Widget", 9.99, VariableNames=["ID", "Name", "Price"]);
sqlwrite(conn, "products", data); % Error if ID is auto-increment
% CORRECT — omit auto-increment column
data = table("Widget", 9.99, VariableNames=["Name", "Price"]);
sqlwrite(conn, "products", data);
```
## Best Practices
- **ALWAYS** use `sqlwrite` for inserting MATLAB tables — it handles type mapping automatically.
- **ALWAYS** prefer `sqlupdate` (R2023a+) over raw SQL UPDATE — it u>
Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.
Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.
Analyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.
S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).
Analyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.
PDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).
Calculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.