Main Content

Import Data from PostgreSQL Database Table

This example shows how to import data from a table in a PostgreSQL database into the MATLAB® workspace using the sqlread and fetch functions with the PostgreSQL native interface.

Connect to Database

Create a PostgreSQL native interface database connection using the data source name PostgreSQLDataSource and a user name and password. The PostgreSQL database contains the table productTable.

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

Import Data from Database Table Using sqlread Function

Import product data from the database table productTable by using the sqlread function and the database connection. This function imports data as a MATLAB table.

tablename = "productTable";
data = sqlread(conn,tablename);

Display the product number and description in the imported data.

data(:,[1 5])
ans=11×2 table
    productnumber    productdescription
    _____________    __________________

          9          "Victorian Doll"  
          8          "Train Set"       
          7          "Engine Kit"      
          2          "Painting Set"    
          4          "Space Cruiser"   
          1          "Building Blocks" 
          5          "Tin Soldier"     
          6          "Sail Boat"       
          3          "Slinky"          
         10          "Teddy Bear"      
         30          "Rubik's Cube"    

Import Data from Database Table Using fetch Function

Import product data from the database table productTable by using the fetch function and the database connection. Create an SQL query to import data that is sorted by product description alphabetically. The fetch function imports data as a MATLAB table.

sqlquery = "SELECT * FROM productTable ORDER BY productDescription ASC";
data = fetch(conn,sqlquery);

Display the product number and description in the imported data.

data(:,[1 5])
ans=11×2 table
    productnumber    productdescription
    _____________    __________________

          1          "Building Blocks" 
          7          "Engine Kit"      
          2          "Painting Set"    
         30          "Rubik's Cube"    
          6          "Sail Boat"       
          3          "Slinky"          
          4          "Space Cruiser"   
         10          "Teddy Bear"      
          5          "Tin Soldier"     
          8          "Train Set"       
          9          "Victorian Doll"  

Close Database Connection

close(conn)

See Also

| | |

Related Topics

External Websites