メインコンテンツ

sqlwrite

Insert MATLAB data into database table

Description

sqlwrite(conn,tablename,data) inserts data from a MATLAB® table into a database table.

  • If the specified table already exists in the database, the function appends the rows from the MATLAB table to the existing table.

  • If the table does not exist, the function creates a new table with the specified name and then inserts the data as rows.

This syntax is equivalent to executing SQL statements that use the CREATE TABLE and INSERT INTO commands defined by ANSI SQL.

conn can be any of the following connection objects:

  • MySQL®

  • PostgreSQL®

  • DuckDB™

  • SQLite

  • ODBC

  • JDBC

example

sqlwrite(conn,tablename,data,Name=Value) uses additional options specified by one or more name-value pair arguments. For example, Catalog="toy_store" inserts the data into a database table located in the database catalog named toy_store.

example

Examples

collapse all

Use a MySQL® native interface database connection to append product data from a MATLAB® table into an existing table in a MySQL database.

Create a MySQL native interface database connection to a MySQL database using the data source name, user name, and password. The database contains the table productTable.

datasource = "MySQLNative";
username = "root";
password = "matlab";
conn = mysql(datasource,username,password);

To view the existing database table productTable before appending data, import its contents into MATLAB and display the last few rows.

tablename = "productTable";
rows = sqlread(conn,tablename);
tail(rows,3)
ans=3×5 table
     6    400876    1004     8     "Sail Boat"
     3    400999    1009    17        "Slinky"
    10    888652    1006    24    "Teddy Bear"

Create a MATLAB table that contains the data for one product.

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

Append the product data into the database table productTable.

sqlwrite(conn,tablename,data)

Import the contents of the database table into MATLAB again and display the last few rows. The results contain a new row for the inserted product.

rows = sqlread(conn,tablename);
tail(rows,4)
ans=4×5 table
     6    400876    1004     8       "Sail Boat"
     3    400999    1009    17          "Slinky"
    10    888652    1006    24      "Teddy Bear"
    30    500000    1000    25    "Rubik's Cube"

Close the database connection.

close(conn)

Use a PostgreSQL native interface database connection to insert product data from MATLAB® into a new table in a PostgreSQL database.

Create a PostgreSQL native interface database connection to a PostgreSQL database using the data source name, user name, and password.

datasource = "PostgreSQLDataSource";
username = "dbdev";
password = "matlab";
conn = postgresql(datasource,username,password);

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.

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

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

rows = sqlread(conn,tablename)
rows=2×5 table
    30    500000    1000    25    "Rubik's Cube"
    40    600000    2000    30      "Doll House"

Close the database connection.

close(conn)

Create a transient, in-memory DuckDB™ database connection by using the duckdb function.

conn = duckdb();

Create a table to store product data that includes ID, name, and quantity information.

idData = [1001;1002;1003];
nameData = ["item1";"item2";"item3"];
quantityData = [250;100;400];
varNames = ["ID","Name","Quantity"];
productData = table(idData,nameData,quantityData,VariableNames=varNames)
productData=3×3 table
     ID      Name      Quantity
    ____    _______    ________

    1001    "item1"      250   
    1002    "item2"      100   
    1003    "item3"      400   

Export the table to the DuckDB™ database by using the sqlwrite function.

sqlwrite(conn,"productTable",productData)

Import the table from the DuckDB database into the MATLAB® workspace by using the sqlread function. Confirm that the values in data match the values in productData.

data = sqlread(conn,"productTable")
data=3×3 table
     ID      Name      Quantity
    ____    _______    ________

    1001    "item1"      250   
    1002    "item2"      100   
    1003    "item3"      400   

Close the database connection.

close(conn);

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 an sqlite 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.

close(conn)

Use an ODBC connection to insert product data from MATLAB® into a new table in a Microsoft® SQL Server® database. Insert data stored as a structure into the new database table.

Create an ODBC database connection to a Microsoft SQL Server database with Windows® authentication. Specify a blank user name and password.

datasource = 'MS SQL Server Auth';
conn = database(datasource,'','');

Check the database connection. If the Message property is empty, then the connection is successful.

conn.Message
ans =

     []

Create a structure array that contains data for two products.

s(1).productNumber = 30;
s(1).stockNumber = 500000;
s(1).supplierNumber = 1000;
s(1).unitCost = 25;
s(1).productDescription = "Rubik's Cube";

s(2).productNumber = 40;
s(2).stockNumber = 600000;
s(2).supplierNumber = 2000;
s(2).unitCost = 30;
s(2).productDescription = "Doll House";

Convert the structure to a MATLAB table.

data = struct2table(s);

Insert the product data into a new database table toyTable.

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

Import the contents of the database table into MATLAB and display the rows. The results contain 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'    

Close the database connection.

close(conn)

Input Arguments

collapse all

Database connection, specified as any of the following:

  • MySQL connection object created by using the mysql function.

  • PostgreSQL connection object created by using the postgresql function.

  • DuckDB connection object created by using the duckdb function.

  • SQLite connection object created by using the sqlite function.

  • ODBC connection object created by using the database function.

  • JDBC connection object created by using the database function.

Database table name, specified as a string scalar or character vector.

Example: "employees"

Data Types: string | char

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

MATLAB tables can include the following data types:

  • Numeric arrays

  • Cell array of numeric arrays

  • Cell arrays of character vectors

  • String arrays

  • Datetime arrays

  • Duration arrays

  • Logical arrays

  • Cell arrays of logical arrays

Numeric arrays can contain these data types: int8, uint8, int16, uint16, int32, uint32, int64, uint64, single, or double.

Supported date and time formats are:

  • Date — 'yyyy-MM-dd'

  • Time — 'hh:mm:ss'

  • Timestamp — 'yyyy-MM-dd HH:mm:ss'

If date and time values are in an invalid format, sqlwrite automatically converts them to a supported format.

For string arrays or cell arrays of character vectors, the database driver validates the format. If the format is unexpected, the driver throws an error.

You can insert data into an existing database table or create a new one. The variable data types in data vary depending on whether the database table already exists.

Note

The sqlwrite function supports only the table data type for data. To insert data stored in a structure, cell array, or numeric matrix, convert it to a table using:

  • struct2table

  • cell2table

  • array2table

The sqlwrite function does not support the database preferences NullNumberWrite and NullStringWrite. To insert missing data, see Accepted Missing Data.

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

Data Types for Existing Table

When inserting MATLAB table data into an existing database table, the variable names in the MATLAB table must match the column names in the database table, including case.

Use the data types in the mapping table below to ensure compatibility between MATLAB variables and database columns. For example, if the database column uses the BOOLEAN data type, the corresponding MATLAB variable should be a LOGICAL array or a cell array of logical arrays.

MATLAB DataTypeMySQLPostgreSQLDuckDBSQLiteJDBC/ODBC
numeric array or cell array of numeric arrays

INTEGER

SMALLINT

DECIMAL

NUMERIC

FLOAT

REAL

DOUBLE PRECISION

SMALLINT

INTEGER

BIGINT

DECIMAL

NUMERIC

REAL

DOUBLE PRECISION

SMALLSERIAL

SERIAL

BIGSERIAL

TINYINT

SMALLINT

INTEGER

BIGINT

HUGEINT

UTINYINT

USMALLINT

UINTEGER

UBIGINT

UHUGEINT

FLOAT

DOUBLE

DECIMAL

DOUBLENUMERIC
cell array of character vectors, string array, datetime array, or duration array

DATE

TIME

TIMESTAMP

DATE

TIME

TIMESTAMP

DATE

TIME

TIMESTAMP_WITH_TIMEZONE

N/ATIME
logical array or cell array of logical arraysBITBITBOOLEANDOUBLEBIT or BOOLEAN
cell array of character vectors or string array

CHAR

VARCHAR

CHAR

VARCHAR

VARCHARVARCHAR

CHAR

VARCHAR

TEXT

NTEXT

Other text data type

calendarDuration arrayN/AINTERVALINTERVALN/AN/A

Data Types for New Table

When inserting MATLAB table data into a new database table, sqlwrite:

  • Requires unique table names.

  • Ignores variables with unsupported data types and only inserts valid variables as columns.

  • Maps each MATLAB variable to a default database column type.

The table below shows supported MATLAB data types and their corresponding default database types.

MATLAB Data TypeMySQLPostgreSQLDuckDBSQLiteJDBC/ODBC
int8 arrayTINYINTSMALLINTTINYINTN/AN/A
int16 arraySMALLINTSMALLINTSMALLINTN/AN/A
int32 arrayINTEGERINTEGERINTEGERN/AN/A
int64 arrayBIGINTBIGINTBIGINTN/AN/A
logical arrayBITBOOLEANBOOLEANDOUBLENUMERIC
single or double arrayNUMERICNUMERICFLOAT or DOUBLEN/AN/A
datetime arrayTIMESTAMPTIMESTAMPTIMESTAMPN/ATIMESTAMP
duration arrayTIMETIMETIMEN/ATIME
cell array of character vectors or string arrayVARCHAR *VARCHAR *VARCHARN/AN/A
calendarDuration arrayN/AINTERVALINTERVALN/AN/A
numeric array or cell array of numeric arraysN/AN/ADOUBLEDOUBLENUMERIC
string array, cell array of character vectors, or datetime arraysN/AN/AN/AVARCHARN/A
string arrayN/AN/AN/AN/AVARCHAR
cell array of character vectorsN/AN/AN/AN/AVARCHAR *
* Column size is set to the maximum string length found in the array plus 100 characters.

To use database-specific column data types instead of defaults, specify the ColumnType name-value argument. For example, set ColumnType="BIGINT" to create a column with the BIGINT data type in the new table. ColumnType also allows you to specify other data types, such as "image" or "money", that are not in the above table.

Accepted Missing Data

The accepted missing data values depend on the MATLAB table variable and the database column. The table below maps each MATLAB data type to its database column type and lists the accepted missing data for each case.

Data Type of MATLAB Table VariableData Type of Database ColumnAccepted Missing Data
datetime arrayDATE, TIME, or TIMESTAMPNaT
duration arrayTIMENaN
double or single array
  • NUMERIC

  • DOUBLE

  • FLOAT

  • DECIMAL

  • REAL

NaN
cell array of double or single arrays
  • NUMERIC

  • DOUBLE

  • FLOAT

  • DECIMAL

  • REAL

NaN, [], or ''
cell array of character vectorsDATE, TIME, or TIMESTAMP'NaT' or ''
cell array of character vectorsCHAR, VARCHAR, or other text data type''
string arrayDATE, TIME, or TIMESTAMP"", "NaT", or missing
string arrayCHAR, VARCHAR, or other text data typemissing

Data Types: table

Name-Value Arguments

collapse all

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: sqlwrite(conn,"tablename",data,ColumnType=["numeric" "timestamp" "image"]) inserts data into a new database table named tablename by specifying data types for columns in the new database table.

Database catalog name, specified as a string scalar or character vector. A catalog serves as the container for the schemas in a database and contains related metadata information. A database can have multiple catalogs.

Example: Catalog = "toy_store"

Data Types: string | char

Database schema name, specified as a string scalar or character vector. A schema defines the database tables, views, relationships among tables, and other elements. A database catalog can have numerous schemas.

Example: Schema = "dbo"

Data Types: string | char

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

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

Data Types: string | char | cell

Table existence, specified as true or false.

  • truesqlwrite checks for table existence and automatically creates one if it does not exist.

  • falsesqlwrite does not check for table existence.

Example: sqlwrite(conn,tableName,table(data,'VariableNames',{'COL1'}),checkTableExists=false);

Version History

Introduced in R2018a

expand all