0

Rust – Connect to PostgreSQL

Last Updated on

This post is about how to connect to PostgreSQL from Rust.

Requirements

Database Table

We have this table structure for our codes and testing.

Sample data:

Update Cargo.toml

Under the [dependencies]  section, add the postgres = "0.15.2" :

Rust Codes

Before we create the codes to connect to PostgreSQL and retrieve data from it, we need to reference to postgres crate as follows.

Then, we need to create a struct that resembles and represents the students table.

The main function

In the main function, we first get a connection:

Note that we are passing both the database user name and password. In addition to that, we are not using TLS.

With a database connection, we can now retrieve records from a table.

Output

When we run our application, we get the following output.

Avatar

Karl San Gabriel

Professional Software Developer