rust操作pgsql、mysql和sqlite
rust中,有很多技术可以操作pgsql、mysql和sqlite,以sqlx为主流技术。我们以sqlx操作sqlite为示例,操作pgsql和mysql的办法是一样的。
Cargo.toml:
[package]
name = "test"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version ="0.8.3", features = [ "runtime-tokio", "tls-rustls-ring", "mysql","postgres","sqlite", "time", "uuid", "chrono" ] }
axum = { version ="0.7.7", features = ["multipart"] }
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-appender = "0.2"
futures = "0.3.31"
tower-http = { version ="0.6.1", features = ["cors", "fs", "compression-gzip"] }
chrono = { version = "0.4", features = ["serde"] }
tokio-util = { version = "0.7", features = ["io","compat"] }
tower="0.5.1"
thiserror = "1.0"
main.rs:
use crate::entity::*;
use axum::routing::post;
use axum::{
extract::Extension, http::StatusCode, response::IntoResponse, routing::get, Json, Router,
};
use axum::{
extract::State,
extract::{Path, Query},
};
use axum::{
extract::{FromRef, FromRequestParts},
http::request::Parts,
};
use serde::{Deserialize, Serialize};
use std::{env, option};
use thiserror::Error;
use tokio_stream::StreamExt; // 用于处理异步流
mod entity;
use axum::extract::DefaultBodyLimit;
use axum::extract::Query as axumQuery;
use sqlx::encode::IsNull;
use sqlx::mysql::{MySqlPool, MySqlPoolOptions};
use sqlx::postgres::{PgPool, PgPoolOptions};
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::sqlite::{SqliteOperation, SqlitePool};
use sqlx::{mysql::MySqlQueryResult, mysql::MySqlRow, postgres::PgQueryResult, postgres::PgRow, Sqlite};
use sqlx::{sqlite::SqliteQueryResult, sqlite::SqliteRow, Column, FromRow, Row, TypeInfo};
use std::collections::HashMap;
use std::error::Error;
use std::path::Path as stdPath;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::net::TcpStream;
use tokio::process::Command; // 使用 tokio 的异步 Command
use tokio::task;
use tokio_util::compat::TokioAsyncWriteCompatExt;
use tower_http::cors::{Any as OtherAny, CorsLayer};
use tracing::{debug, info, warn};
use tracing_appender::rolling;
use tracing_subscriber::fmt::writer::MakeWriterExt;
use oracle::sql_type;
use libloading::{Library, Symbol};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::os::raw::c_int;
use sysinfo::{System};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::sync::Arc;
use once_cell::sync::Lazy;
use std::sync::Mutex;
#[tokio::main]
async fn main() {
//创建连接
let database_url = "sqlite::memory:";
let sqliteconnection = SqlitePoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("数据库连接失败");
let create_table_1 = "CREATE TABLE test(c1 TEXT COLLATE NOCASE , c2 TEXT COLLATE NOCASE );";
//执行sql语句
sqlx::query(create_table_1)
.execute(&sqliteconnection )
.await
.expect("创建表失败");
}
代码来源为hpctb真实代码的简化。