SQL Server Dynamically pass the SQL parameter in Go

zmeyuzjn  于 2023-04-10  发布在  Go
关注(0)|答案(2)|浏览(167)

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)
    }
}
rta7y2nd

rta7y2nd1#

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, "%")) }

9cbw7uwe

9cbw7uwe2#

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.

相关问题