sqlwrite - Insert MATLAB data into SQLite database table - MATLAB (original) (raw)

Insert MATLAB data into SQLite database table

Since R2022a

Syntax

Description

sqlwrite([conn](#mw%5Fa367c3c4-1064-4805-a232-f1b8ef5fcfa6%5Fsep%5Fshared-conn),[tablename](#mw%5Fa367c3c4-1064-4805-a232-f1b8ef5fcfa6%5Fsep%5Fshared-tablename),[data](#mw%5F15a0a572-afe9-4d62-b8d4-0ac24c8ed908)) inserts data from a MATLAB® table into a database table with the MATLAB interface to SQLite. If the table exists in the database, this function appends the data in the MATLAB table as rows in the existing database table. If the table does not exist in the database, this function creates a table with the specified table name and then inserts the data as rows in the new table. This syntax is the equivalent of executing SQL statements that contain the CREATE TABLE and INSERT INTO ANSI SQL syntaxes.

example

sqlwrite([conn](#mw%5Fa367c3c4-1064-4805-a232-f1b8ef5fcfa6%5Fsep%5Fshared-conn),[tablename](#mw%5Fa367c3c4-1064-4805-a232-f1b8ef5fcfa6%5Fsep%5Fshared-tablename),[data](#mw%5F15a0a572-afe9-4d62-b8d4-0ac24c8ed908),ColumnType=[columntypes](#mw%5F5dadcf51-6e31-48d9-ba6e-d264b272ae42)) specifies the data type for the column in the SQLite database.

example

Examples

collapse all

Append Data into Existing Table

Use the MATLAB interface to SQLite to append data from a MATLAB table into an existing table in an SQLite database.

First, create an SQLite connection to the file sample_dataset.db that contains the table airlinesmall. The SQLite connectionconn is an SQLite object.

dbfile = fullfile(matlabroot,"toolbox/database/database/sample_dataset.db"); conn = sqlite(dbfile);

Import the contents of airlinesmall into MATLAB and display the last few rows.

tablename = "airlinesmall"; query = strcat("SELECT YEAR, MONTH, DayOfMonth, DayOfWeek," + ... "DepTime, ArrTime FROM ", tablename); rows = fetch(conn,query); tail(rows,3)

YEAR    MONTH    DayofMonth    DayOfWeek    DepTime    ArrTime
____    _____    __________    _________    _______    _______

2008      2           6            3         1909       2027  
2008      2          12            2          718        844  
2008      2          15            5         1650       1951  

Create a new MATLAB table by extracting the last row and change the departure time by changingDepTime to 1950.

data = tail(rows,1); data.DepTime = 1950;

Append the new data table into airlinesmall by usingsqlwrite. Then, import the contents ofairlinesmall into MATLAB again and verify that the last row is the appended data with the updated departure time.

sqlwrite(conn,tablename,data); rows = fetch(conn,query); tail(rows,4)

YEAR    MONTH    DayofMonth    DayOfWeek    DepTime    ArrTime
____    _____    __________    _________    _______    _______

2008      2           6            3         1909       2027  
2008      2          12            2          718        844  
2008      2          15            5         1650       1951  
2008      2          15            5         1950       1951  

Close the database connection.

Insert Data into New Table

Use the MATLAB interface to SQLite to insert product data from MATLAB into a new table in an SQLite database.

Create an SQLite connection conn to the existing SQLite database file sample_dataset.db. The SQLite connection is ansqlite object.

dbfile = fullfile(matlabroot,"toolbox/database/database/sample_dataset.db"); conn = sqlite(dbfile);

Create a MATLAB table that contains data for two products.

data = table([30;40],[500000;600000],[1000;2000],[25;30], ... ["Rubik's Cube";"Doll House"],'VariableNames',["productNumber" ... "stockNumber" "supplierNumber" "unitCost" "productDescription"]);

Insert the product data into a new database table namedtoyTable.

tablename = "toyTable"; sqlwrite(conn,tablename,data)

Import the contents of the database table into MATLAB and display the rows. The output contains two rows for the inserted products.

rows = sqlread(conn,tablename)

rows=2×5 table productNumber stockNumber supplierNumber unitCost productDescription _____________ ___________ ______________ ________ __________________

     30             5e+05            1000            25         "Rubik's Cube"  
     40             6e+05            2000            30         "Doll House"    

Delete the new table to maintain the dataset.

sqlquery = "DROP TABLE toyTable"; execute(conn,sqlquery)

Close the database connection.

Specify Column Types When Inserting Data into New Table

Use the MATLAB interface to SQLite to insert product data from MATLAB into a new table in an SQLite database. Specify the data types of the columns in the new database table.

Create an SQLite connection conn to the existing SQLite database file sample_dataset.db. The SQLite connection is ansqlite object.

dbfile = fullfile(matlabroot,"toolbox/database/database/sample_dataset.db"); conn = sqlite(dbfile);

Create a MATLAB table that contains data for two products.

data = table([30;40],[500000;600000],[1000;2000],[25;30], ... ["Rubik's Cube";"Doll House"],'VariableNames',["productNumber" ... "stockNumber" "supplierNumber" "unitCost" "productDescription"]);

Insert the product data into a new database table named toyTable. Use the ColumnType name-value argument and a string array to specify the data types of all the columns in the database table.

tablename = "toyTable"; coltypes = ["numeric" "numeric" "numeric" "numeric" "varchar(255)"]; sqlwrite(conn,tablename,data,ColumnType=coltypes)

Import the contents of the database table into MATLAB and display the rows. The output contains two rows for the inserted products.

rows = sqlread(conn,tablename)

rows=2×5 table productNumber stockNumber supplierNumber unitCost productDescription _____________ ___________ ______________ ________ __________________

     30            500000            1000            25         "Rubik's Cube"  
     40            600000            2000            30         "Doll House"    

Delete the new table to maintain the dataset.

sqlquery = "DROP TABLE toyTable"; execute(conn,sqlquery)

Close the database connection.

Input Arguments

collapse all

SQLite database connection, specified as an sqlite object created using the sqlite function.

Database table name, specified as a string scalar or character vector denoting the name of a table in the database.

Example: "employees"

Data Types: string | char

data — Data to insert

table

Data to insert into a database table, specified as a table.

The valid data types in a MATLAB table are:

The numeric array can contain these data types:

For date and time data, supported formats are:

If the date and time data is specified in an invalid format, then thesqlwrite function automatically converts the data to a supported format.

If the cell array of character vectors or string array is specified in an invalid format, then the sqlwrite function enables the database driver to check the format. If the format is unexpected, then the database driver throws an error.

You can insert data in an existing database table or a new database table. The data types of variables in data vary depending on whether the database table exists. For valid data types, see Data Types for Existing Table and Data Types for New Table.

Note

The sqlwrite function supports only thetable data type for the data input argument. To insert data stored in a structure, cell array, or numeric matrix, convert the data to a table by using the struct2table, cell2table, and array2table functions, respectively.

Example: table([10;20],{'M';'F'})

Data Types for Existing Table

The variable names of the MATLAB table must match the column names in the database table. Thesqlwrite function is case-sensitive.

When you insert data into a database table, use the data types shown in the following table to ensure that the data has the correct data type. This table matches the valid data types of the MATLAB table variable to the data types of the database column. For example, when you insert data into a database column that has the BOOLEAN data type, ensure that the corresponding variable in the MATLAB table is a logical array or cell array of logical arrays.

Data Type of MATLAB Table Variable Data Type of Existing Database Column
Numeric array or cell array of numeric arrays DOUBLE
String arrayCell array of character vectorsDatetime array VARCHAR
Logical array DOUBLE

Data Types for New Table

The specified table name for the new database table must be unique across all tables in the database.

The valid data types in a MATLAB table are:

The sqlwrite function ignores any invalid variable types and inserts only the valid variables from MATLAB as columns in a new database table.

The sqlwrite function converts the data type of the variable into the default data type of the column in the database table. The following table matches the valid data types of the MATLAB table variable to the default data types of the database column.

Data Type of MATLAB Table Variable Default Data Type of Database Column
Numeric array or cell array of numeric arrays DOUBLE
String arrayCell array of character vectorsDatetime array VARCHAR
Logical array DOUBLE

To specify database-specific column data types instead of the defaults, use theColumnType name-value argument. For example, you can specifyColumnType="DOUBLE" to create a DOUBLE column in the new database table.

Accepted Missing Data

The accepted missing data for inserting data into a database depends on the data type of the MATLAB table variable and the data type of the column in the database. The following table matches the data type of the MATLAB table variable to the data type of the database column and specifies the accepted missing data to use in each case.

Data Type of MATLAB Table Variable Accepted Missing Data
Numeric array NaN
String array missing
Cell array of character vectors ''
Datetime array NaT

Data Types: table

columntypes — Database column types

character vector | string scalar | cell array of character vectors | string array

Database column types, specified as a character vector, string scalar, cell array of character vectors, or string array. Use this argument to define custom data types for the columns in a database table. Specify a column type for each column in the table.

Example: ["numeric" "varchar(400)"]

Data Types: cell | char | string

Version History

Introduced in R2022a