PostgreSQL, Rust, Software Development

Rust – Connect to PostgreSQL Database Using Crate

Is this your sudden foray into Rust? Although not totally for beginners, this post shows how to connect to a PostgreSQL database from Rust. Note that we have updated the content of this post to use a newer version of postgres crate.

Rust and PostgreSQL Requirements

PostgreSQL Database Table And Test Data

Before running any Rust codes and connecting to PostgreSQL, please ensure we have a running instance of a PostgreSQL database with a table and test data. This post uses a specific database table which we can create by running the following SQL DDL against PostgreSQL.

The students table has only two fields – an auto-incrementing field and a string field. Then, insert some data into the table.

Create a Rust Project With Dependency on Postgres crate

Next, we create a Rust project with a dependency on the postgres crate, as shown below. Under the [dependencies]  section, add the postgres = "0.19.1".

Rust Codes To Connect To PostgreSQL

Before we create the codes to connect to PostgreSQL and retrieve data, we need to import some structs from the postgres crate, as shown below. We will use these structs to connect to the database.

Then, we need to create a struct that represents the students table in our database. The struct has only two fields like the students table.

Next, we modify the main function. As the first line of the function, get a connection using the following line of codes. These very Rust codes connect to the PostgreSQL database. Note that we are passing both the database user name and password. In addition to that, we are not using TLS.

Now with a database connection, we can retrieve records from a table.

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

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like