如何在sqlx中运行纯SQL语句?

huangapple go评论104阅读模式
英文:

How to run pure sql in sqlx

问题

sqlx扩展了database/sql库,并具有Exec|Query函数,用于运行没有参数的纯SQL语句。但是,当我尝试运行sqlx.Exec时,它显示“sqlx没有Exec函数”。如何让sqlx运行没有任何参数的纯SQL方法?

英文:

The sqlx extends the database/sql library and have Exec|Query function to run the pure sql without argument, but when i tried to run sqlx.Exec it said the sqlx have no Exec function. How to let sqlx run the pure sql method without any argument?

答案1

得分: 4

github.com/jmoiron/sqlx 是一个。包没有方法,但可以有函数

类型可以有方法。sqlx.DB 类型是你要找的。它嵌入了 *sql.DB 类型,该类型有一个 DB.Exec() 方法,该方法被提升并且在类型为 *sqlx.DB 的值上也可用。

所以首先你需要一个 *sqlx.DB 值,通过连接到数据库,类似这样:

db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
if err != nil {
    log.Fatalln(err)
}

这里的 db 是类型为 *sqlx.DB。然后你可以使用 Exec() 方法:

result, err := db.Exec("SELECT * FROM mytable")
英文:

The github.com/jmoiron/sqlx is a package. Packages do not have methods, they may have functions.

Types may have methods. The sqlx.DB type is what you're looking for. It embeds the *sql.DB type which have a DB.Exec() method, which is promoted and is available on a value of type *sqlx.DB too.

So first you need an *sqlx.DB value, by connecting to the database, something like this:

db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
if err != nil {
    log.Fatalln(err)
}

Here db is of type *sqlx.DB. Then you may use the Exec() method:

result, err := db.Exec("SELECT * FROM mytable")

huangapple
  • 本文由 发表于 2021年11月12日 16:25:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/69939883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定