%% Append Data into Existing Table Using PostgreSQL Native Interface
% Use a PostgreSQL native interface database connection to append product data from a MATLAB® table into an existing 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. The database contains the table productTable.

datasource = "PostgreSQLDataSource";
username = "dbdev";
password = "matlab";
conn = postgresql(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)

%
% 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)

%
% Close the database connection.

close(conn)

% Copyright 2020 The MathWorks, Inc.