%% Import Data from SQL Query as Structure
% Specify the data return format and the number of imported rows for the results of an SQL query. Import data using the SQL query and the fetch function.
% This example uses a PostgreSQL database version 9.405 database and the libpq driver version 10.12.
%
% Create a PostgreSQL native interface database connection to a PostgreSQL database with a data source name, user name, and password.

datasource = "PostgreSQLDataSource";
username = "dbdev";
password = "matlab";

conn = postgresql(datasource,username,password);

%
% Load patient information into the MATLAB® workspace.

patients = readtable('patients.xls');

%
% Create the patients database table using the patient information.

tablename = "patients";
sqlwrite(conn,tablename,patients)

%
% Select all data from the patients database table and import five rows from the table as a structure. Use the 'DataReturnFormat' name-value pair argument to specify returning the data as a structure. Also, use the 'MaxRows' name-value pair argument to specify five rows. Display the imported data.

sqlquery = strcat("SELECT * FROM ",tablename);
results = fetch(conn,sqlquery,'DataReturnFormat',"structure", ...
    'MaxRows',5)

%
% Delete the patients database table using the execute function.

sqlquery = strcat("DROP TABLE ",tablename);
execute(conn,sqlquery)

%
% Close the database connection.

close(conn)

% Copyright 2020 The MathWorks, Inc.