亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

編寫一個可以使用 2 個數據庫的應用程序?

編寫一個可以使用 2 個數據庫的應用程序?

Go
胡說叔叔 2023-07-17 14:20:28
我正在嘗試用 Go 編寫一個應用程序,能夠根據配置連接到 oracle 和 MySQL。我現在遇到的問題是當我使用準備好的語句時。例如,考慮下面的查詢Select * from data_table where id = 1下面給出MySQL和oracle中對應的prepared語句MySQL -> Select * from data_table where id = ? ORACLE -> Select * from data_table where id = :val1如果是這樣,我維護 2 組查詢并根據配置選擇查詢。有一個更好的方法嗎?我想避免保留兩組查詢的麻煩
查看完整描述

1 回答

?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

這很大程度上是通過使用接口來實現的。


假設您創建一個 Web 應用程序并且想要顯示用戶。


首先,您需要定義一個接口,例如


type Creator interface{

  Create(u User)(User,error)

}


type Reader interface{

  Read(k PrimaryKey)(User, error)

  ListAll()([]User,error)

  ListPaginated(page, offset int)([]User,error)

}


type Updater interface{

  Update(u User)(User, error)

  UpdateByKey(k PrimaryKey, u User)(User, error)

  UpdateMany(...User)error

}


type Deleter interface{

  Delete(u User)error

  DeleteMany(u ...User)error

  DeleteByKey(keys ...PrimaryKey)error

}


type CRUD interface {

  Creator

  Reader

  Updater

  Deleter

}

接下來,為您想要支持的每種數據庫類型實現 CRUD 接口。


現在,您可以創建一個處理程序:



// ListHandler uses an interface instead of a concrete type to

// retrieve the data from the databases.

// Not only does this approach make it possible to provide different

// implementations, but it makes unit testing way easier.

//

// "Thou Shalt Write Tests"

func ListHandler(rdr Reader) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {


        // Pagination ommited for brevity


        // Note that the handler is agnostic of the underlying implementation.

        u, err := rdr.ListAll()

        if err != nil {

            log.Printf("ListHandler: error retrieving user list: %s", err)

            // Do not do this in production! It might give an attacker information

            // Use a static error message instead!

            http.Error(w, err.Error(), http.StatusInternalServerError)

            return

        }


        if err := json.NewEncoder(w).Encode(u); err != nil {

            log.Printf("ListHandler: error encoding user list to JSON: %s", err)

            // See above

            http.Error(w, err.Error(), http.StatusInternalServerError)

        }

    })

}

并設置如下:



func main() {

    // Get your config

    // Then simply use an implementation of CRUD


    var dbConn CRUD

    switch cfg.DbType {

    case "myql":

        // returns your implementation of CRUD using MySQL

        dbConn = createMySQLConnector(cfg)

    case "oracle":

        // returns your implementation of CRUD using Oracle

        dbConn = createOracleConnector(cfg)

    }


    http.Handle("/users/", ListHandler(dbConn))


    log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))

}


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號