rust初学记录-db2访问

原创
03/09 17:00
阅读数 140

 

Cargo.toml

[package]
name = "test_rust_actix_db2"
version = "0.1.0"
authors = ["xxx <xxx@xxx>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "3"
#唯一ID
uuid = { version = "0.8", features = ["serde", "v4"] }
#日志
log = "0.4.14"
env_logger = "0.8"
#数据库连接池
r2d2 = "0.8"
ibm_db = { git = "https://github.com/ibmdb/rust-ibm_db.git",branch="main" }
#延迟加载全局变量
lazy_static = "1.4"
#json
serde_derive = "1.0"
#json
serde_json = "1.0"
[profile.release]
lto = true
opt-level = 'z'

 先制造一个连接池

use ibm_db::{ODBCConnectionManager,Statement,ResultSetState::Data};
use std::sync::Mutex;
use std::env;
pub mod db2query;
//获取连接池
pub fn getPool() -> r2d2::Pool<ODBCConnectionManager> {

    let manager = ODBCConnectionManager::new(
        format!("DATABASE={};HOSTNAME={};PORT={};UID={};PWD={};"
        ,env::var("DATABASE").unwrap()
        ,env::var("HOSTNAME").unwrap()
        ,env::var("PORT").unwrap()
        ,env::var("UID").unwrap()
        ,env::var("DBPWD").unwrap()
        )
        
        );
        r2d2::Pool::new(manager).unwrap()    
}

lazy_static! { 
    pub static ref DB2POOL: r2d2::Pool<ODBCConnectionManager>= {
       
        getPool()
    };
}

 

由于没有合适的orm ,先临时做一个查询封装

use std::collections::HashMap;
use crate::dboper;
use ibm_db::{Statement,ResultSetState::Data};

pub fn query_list(sql : String) -> Vec<HashMap<String,String>>{
    
    let pool_conn = dboper::db2::DB2POOL.get().unwrap();
    
    let conn = pool_conn.raw();

    let mut result :Vec<HashMap<String,String>> = Vec::new();
            let stmt = Statement::with_parent(&conn).unwrap();
            if let Data(mut stmt) = stmt.exec_direct(&sql).unwrap() {
                let cols = stmt.num_result_cols().unwrap();
                let mut columns :Vec<String> =Vec::new();

                for index in 1..cols {
                   let desc:String =stmt.describe_col(index.to_owned() as u16).unwrap().name;
                   columns.push(desc) ;
                }
                //println!("columns.len()={}",columns.len());

                

                while let Some(mut cursor) = stmt.fetch().unwrap(){
                    let mut row:HashMap<String,String> =HashMap::new();
                    
                    for _i in 1..cols {
                        let fieldname :String =format!("{}",columns[(_i as usize)-1]);
                        match cursor.get_data::<String>(_i as u16).unwrap() {
                            Some(val) => {
                               //println!("{},{}",&fieldname,&val); 
                               row.insert(fieldname,String::from(val));
                            },
                            None => {
                                //println!("{},NULL",&fieldname);
                            },
                        }
                    }
                    result.push(row);
                }


            };

            
            result
    
}

restful输出

use actix_web::{get, HttpResponse, Responder};
use std::collections::HashMap;
use crate::dboper::db2::db2query::query_list;
use serde_json;
#[get("/group/list")]
pub async fn grouplist() -> impl Responder {

    let result : Vec<HashMap<String,String>> =query_list(String::from("select groupid ,groupname,nvl(remark,'--') remark from wf_group"));
    HttpResponse::Ok()
    .content_type("application/json;charset=utf-8")
    .body(
        serde_json::to_string(
            &result
        ).unwrap()

   )
}

构建镜像,由于DB cli 不支持musl ,所以使用ubuntu作为运行镜像

# ------------------------------------------------------------------------------
# Cargo Build Stage
# ------------------------------------------------------------------------------

FROM accuminium/rust-ubuntu:20.10_stable as cargo-build
USER root
RUN mkdir -p /opt


COPY linuxx64_odbc_cli.tar.gz /opt/clidriver.tar.gz
WORKDIR /opt
RUN tar zxvf /opt/clidriver.tar.gz
RUN rm -f /opt/clidriver.tar.gz

RUN  sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
RUN  apt-get clean


ARG OPENSSL_VERSION=1.1.1i
RUN  apt-get update
RUN DEBIAN_FRONTEND=noninteractive   apt-get install -y  --no-install-recommends git libxml2-dev gcc openssl  libssl-dev build-essential cmake  graphviz libpq-dev libsqlite-dev linux-libc-dev pkgconf  xutils-dev unixodbc-dev && apt-get clean && rm -rf /var/cache/apk/*


RUN  rustup default stable
RUN  rustup target add x86_64-unknown-linux-gnu
ARG CARGO_CONFIG="/usr/local/cargo/config"
RUN mkdir -p /usr/local/cargo
COPY docker/.cargo/config /usr/local/cargo/
RUN export CARGO_HTTP_DEBUG=true
RUN export CARGO_LOG=cargo::ops::registry=debug
RUN mkdir -p /usr/src/test_rust_actix_db2
WORKDIR /usr/src/test_rust_actix_db2
COPY Cargo.toml Cargo.toml
RUN mkdir src/
ARG CARGO_HTTP_MULTIPLEXING=false
ARG CARGO_HTTP_CHECK_REVOKE=false


RUN echo "fn main() {println!(\"if you see this, the build broke\")}" > src/main.rs
RUN  RUSTFLAGS=-Clinker=gcc cargo build -v --release --target=x86_64-unknown-linux-gnu
RUN rm -f target/x86_64-unknown-linux-gnu/release/deps/test_rust_actix_db2*
COPY src ./src
RUN  RUSTFLAGS=-Clinker=gcc cargo rustc -v --release --target=x86_64-unknown-linux-gnu -- -C link-arg="-L/opt/clidriver/lib"
# ------------------------------------------------------------------------------
# Final Stage
# ------------------------------------------------------------------------------

FROM ubuntu:20.10
USER root


COPY linuxx64_odbc_cli.tar.gz /opt/clidriver.tar.gz
WORKDIR /opt
RUN tar zxvf /opt/clidriver.tar.gz
RUN rm -f /opt/clidriver.tar.gz


RUN  sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
RUN  apt-get clean



RUN  apt-get update

RUN DEBIAN_FRONTEND=noninteractive  apt-get install -y libxml2-dev unixodbc-dev  && apt-get clean && rm -rf /var/cache/apk/*


WORKDIR /opt
COPY --from=cargo-build /usr/src/test_rust_actix_db2/target/x86_64-unknown-linux-gnu/release/test_rust_actix_db2 .

EXPOSE 8080
ENTRYPOINT LD_LIBRARY_PATH=/opt/clidriver/lib  ./test_rust_actix_db2

启动服务(由于数据库是GBK的,所以设置DB2CODEPAGE=1208)

docker run -it -p 8080:8080  -e HOSTNAME=XXXX -e DATABASE=XXXX -e PORT=XXX -e UID=xxxx -e DBPWD=XXX -e RUST_BACKTRACE=full -e  DB2CODEPAGE=1208  test_rust_actix_db2

访问

http://[宿主机IP]:8080/group/list

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部