使用 Go 执行 SQL 查询时如何从 db.Exec 获取输出消息
我有一个 Postgres 数据库,通常当您从 psql 执行命令时,您会得到某种输出,如下例所示,
test=> CREATE SCHEMA IF NOT EXISTS algo;
NOTICE: schema "algo" already exists, skipping
CREATE SCHEMA
test=> CREATE SCHEMA IF NOT EXISTS algo2;
CREATE SCHEMA
在 go 中使用 sql 客户端时,我没有找到获取这些输出消息的方法。 db.Exec
函数返回 sql.Result
,其中包含 LastInsertId
和 RowsAffected
,但没有输出消息。可以用go中的sql客户端来实现吗?
这是我的 Go 代码。
package main
import (
"database/sql"
"fmt"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+" dbname=%s password=%s sslmode=disable", host, port, user, dbname, password)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
res, err := db.Exec("CREATE SCHEMA IF NOT EXISTS algo;")
if err != nil {
panic(err)
}
lastInsert, _ := res.LastInsertId()
RoswAffected, _ := res.RowsAffected()
fmt.Println(lastInsert, RoswAffected)
// output: 0 0
}
I have a Postgres database, normally when you execute commands from psql you get some sort of an output like in the example bellow
test=> CREATE SCHEMA IF NOT EXISTS algo;
NOTICE: schema "algo" already exists, skipping
CREATE SCHEMA
test=> CREATE SCHEMA IF NOT EXISTS algo2;
CREATE SCHEMA
I didn't find a way to get these output messages when using an sql client in go. The db.Exec
function is returning sql.Result
which has LastInsertId
and RowsAffected
but no output message. Is it possible to do it with sql client in go?
here is my Go code.
package main
import (
"database/sql"
"fmt"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+" dbname=%s password=%s sslmode=disable", host, port, user, dbname, password)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
res, err := db.Exec("CREATE SCHEMA IF NOT EXISTS algo;")
if err != nil {
panic(err)
}
lastInsert, _ := res.LastInsertId()
RoswAffected, _ := res.RowsAffected()
fmt.Println(lastInsert, RoswAffected)
// output: 0 0
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论