在Go中动态传递SQL参数

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

Dynamically pass the SQL parameter in Go

问题

我有以下的Go程序,它可以动态地传递一个参数。根据我的需求,我事先不知道参数名和参数值。我可能需要以动态的方式传递1...n个参数和对应的值到查询中。我该如何实现这个功能?

import (
    "database/sql"
    "fmt"
)

func main() {
    // 打开与数据库的连接
    db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // 准备带有参数占位符的SQL语句
    stmt, err := db.Prepare("SELECT * FROM mytable WHERE mycolumn = ?")
    if err != nil {
        panic(err)
    }
    defer stmt.Close()

    // 使用参数值执行SQL语句
    rows, err := stmt.Query("myvalue")
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    // 遍历结果集
    for rows.Next() {
        var id int
        var name string
        err := rows.Scan(&id, &name)
        if err != nil {
            panic(err)
        }
        fmt.Println(id, name)
    }
    if err = rows.Err(); err != nil {
        panic(err)
    }
}

你可以使用stmt.Query方法来执行带有参数的SQL语句。在stmt.Query方法中,你可以传递参数的值作为参数。在循环中,你可以使用rows.Scan方法来获取每一行的结果。

英文:

I have the below Go program, which works fine for dynamically passing only one parameter. In my requirement, I will not know the parameter name and parameter value in advance. I may need to pass 1...n parameter to the query and values as dynamic manner. How can I achieve the same?

import (
    "database/sql"
    "fmt"
)

func main() {
    // Open a connection to the database
    db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Prepare the SQL statement with placeholders for the parameters
    stmt, err := db.Prepare("SELECT * FROM mytable WHERE mycolumn = ?")
    if err != nil {
        panic(err)
    }
    defer stmt.Close()

    // Execute the SQL statement with the parameter values
    rows, err := stmt.Query("myvalue")
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    // Iterate over the result set
    for rows.Next() {
        var id int
        var name string
        err := rows.Scan(&id, &name)
        if err != nil {
            panic(err)
        }
        fmt.Println(id, name)
    }
    if err = rows.Err(); err != nil {
        panic(err)
    }
}

答案1

得分: 2

最简单的方法是使用Squirrel。你可以像他们的readME.md中给出的示例那样添加条件查询。

if len(q) > 0 {
    users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%"))
}
英文:

The easiest way would be using Squirrel.
You can add conditional queries like in the example given in their readME.md.

> if len(q) > 0 {
> users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%"))
> }

答案2

得分: 1

我对Go了解甚少(我在这里是因为我了解SQL Server),但我可以找到文档,并看到以下内容:

> Query使用给定的参数执行准备好的查询语句

使用复数的"参数"而不是"参数",再加上我在其他环境中使用?占位符的经验,告诉我你可以将多个参数传递给Query(),它们将被解释为位置参数:

stmt.Query("myvalue1", "myvalue2",.... "myvaluen")

其中,myvalue1与SQL命令字符串中的第一个准备好的?占位符匹配,myvalue2与第二个占位符匹配,依此类推。

我想你已经知道这一点,但为了完整起见,我需要补充一点:不要使用字符串操作将这些值包含在SQL命令中。

英文:

I know very little about Go (I'm here because I do know SQL Server), but I can find the documentation, and see this:

> Query executes a prepared query statement with the given arguments

The use of the plural "arguments", instead of "argument", plus my experience using the ? placeholder in other environments, tells me you can pass multiple arguments to Query() and they will be interpreted as positional parameters:

stmt.Query("myvalue1", "myvalue2",.... "myvaluen")

Where myvalue1 matches to the first prepared ? placeholder in the SQL command string, myvalue2 matches to the second, and so on.

I think you know this, but for completeness I need to add: do NOT use string manipulation to include these values in the SQL command.

huangapple
  • 本文由 发表于 2023年4月4日 05:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923741.html
匿名

发表评论

匿名网友

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

确定