编写一个可以使用 2 个数据库的应用程序?
时间:2024-04-15
浏览:318
作者:佚名
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《编写一个可以使用 2 个数据库的应用程序?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
问题内容
我正在尝试用 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 组查询并根据配置选择查询。有更好的方法吗?
我想避免保留 2 组查询的麻烦
解决方案
这很大程度上是通过使用接口来实现的。
假设您创建了一个 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))
}
第
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
