This is an minimal working example of using rust and axum to connect to a database.
Created
September 29, 2023 06:51
-
-
Save VictorieeMan/ec264768e7c195d7af9cf9d6758a2e5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "axum_seo_tool" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
axum = "0.6.20" | |
tokio = {version="1.32.0", features=["full"]} | |
sqlx = {version="0.7.2", features = ["sqlite", "runtime-tokio-rustls"]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use sqlx::sqlite::SqlitePool; | |
use sqlx::Row; | |
use axum::{ | |
routing::get, | |
Router, | |
}; | |
async fn init_db_pool() -> SqlitePool { | |
let db_url = "./test.db"; | |
let db_pool = SqlitePool::connect(db_url) | |
.await | |
.expect("Failed to connect to the database"); | |
// Create the table if it doesn't exist | |
let create_table_query = r#" | |
CREATE TABLE IF NOT EXISTS your_table ( | |
id INTEGER PRIMARY KEY, | |
name TEXT | |
) | |
"#; | |
sqlx::query(&create_table_query) | |
.execute(&db_pool) | |
.await | |
.expect("Failed to create the table"); | |
db_pool | |
} | |
#[tokio::main] | |
async fn main() { | |
let db_pool = init_db_pool().await; | |
// Create an Axum app with a single route | |
let app = Router::new().route("/", get(move || { | |
let db_pool = db_pool.clone(); | |
async move { | |
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM your_table") | |
.fetch_one(&db_pool) | |
.await | |
.expect("Failed to fetch count"); | |
format!("Hello, World! There are {} records in the database.", count) | |
} | |
})); | |
// Configure and run the Axum server | |
let addr = "0.0.0.0:3000".parse().unwrap(); | |
axum::Server::bind(&addr) | |
.serve(app.into_make_service()) | |
.await | |
.unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment