Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Rust connect to PostgreSQL database

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "Rust how to connect PostgreSQL database", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Rust how to connect PostgreSQL database" bar!

Pgxr is a Rust crate library, which can be used to write PostgreSQL extension functions (equivalent to stored procedures) in Rust language.

This time, we use postgres, the crate, to connect and manipulate the PostgreSQL database.

After you have created the project, add postgres dependencies to cargo.toml:

First, import the relevant types and create a Person struct:

Then create the create_db function, which is used to create databases and tables, and it returns a Result, which may be Client or error:

Note that the connection string accepted by the Client::connect () function can be in two forms:

Key-Value form. For example: Client::connect ("host=localhost user=postgres", NoTls); specific key needs to consult the official documentation. URL form. The URL form is used in this example.

A relatively complete database connection string URL format is:

Postgres://username [: password] @ host [: port] [/ database], where password, port, and database are all optional. So the judgment processing is done in the above code.

The second argument to the Client::connect () function uses NoTls, and for simplicity, we don't use TLS here.

Lines 30 and 32, use the execute method of Client to delete the data table (if it exists) before creating the person table.

Finally, Client is returned.

Next, create an insert_data function to insert some data:

Note that the parameter Client of this function must be mut.

Then create a function to query the data:

Here, we directly iterate over the results returned by the query method of Client, and the final method returns a Vec.

Finally, call these functions in turn in the main function and print out the query results:

The results are as follows:

The full code is as follows:

Use postgres:: {error::Error, Client, NoTls}; # [derive (Debug)] struct Person {id: i32, name: String, data: Option,} fn create_db ()-> Result {let username = "postgres"; let password = "postgres"; let host = "localhost"; let port = "5432"; let database = "rust2021" Let conn_str = & format! ("postgres:// {} @ {}", username, if password.is_empty () {""} else {":"}, password, host, if port.is_empty () {""} else {":"}, port If database.is_empty () {""} else {"/"}, database) Let mut client = Client::connect (conn_str, NoTls)?; let _ = client.execute ("DROP TABLE person", & []); client.execute ("CREATE TABLE person (id SERIAL PRIMARY KEY, name TEXT NOT NULL, data BYTEA)", & [],)? Ok (client) fn insert_data (client: & mut Client)-> Result {let p1 = Person {id: 1, name: "Dave" .to _ string (), data: None,} Let p2 = Person {id: 2, name: "Nick" .to _ string (), "INSERT INTO person (id, name, data) VALUES ($1, $2, $3), ($4, $5, $6)", & [& p1.id, & p1.name, & p1.data, & p2.id, & p2.name, & p2.data] Ok () fn get_data (client: & mut Client)-> Result {let mut persons = Vec::new () For row in client.query ("SELECT id, name, data FROM person", & [])? {persons.push (Person {id: row.get (0), name: row.get (1), data: row.get (2),});} Ok (persons) fn main ()-> Result {let mut client = create_db ()? Insert_data (& mut client)?; let persons = get_data (& mut client); for p in persons {println! ("Person: {:?}", p) Thank you for your reading, the above is the content of "how to connect Rust to PostgreSQL database". After the study of this article, I believe you have a deeper understanding of how Rust connects to PostgreSQL database, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report