What is the recommended way to initialize and save prepared statements in Go?

I am writing my first Go project using sqlx and want to use prepared statements.

I am not sure what the recommended practice is to initialize and save prepared statement variables in a convenient, manageable form.

I want them to be available only from the part of the code that should actually use them, so far each operator is used by one function, so global variables are not a good option (in addition, they are usually underestimated).

In C / C ++, I would probably use a static function variable and initialize it the first time a function is introduced. Thus, the information about the contents of the instruction and the call to it is close to each other.

But from what I know so far, Go has no “static variable methods”, so what's the alternative?

I found links to Closures, anonymous functions, but is this the best for this? Am I aiming for the right thing in terms of “prepared statements of best practices”?

+4
source share
1 answer

, , - , "" (.. , ) , , , .

, , , .

, - :

func main() {

    // initialize your database etc.
    getData, stmt := initGetData(db) // db is *sql.DB, initGetData is the function below
    defer stmt.Close()
    myResult := getData()
}

func initGetData(db *sql.DB) ((func() string), *sql.Stmt) {
    stmt, err := db.Prepare("SELECT something FROM some_table")
    if err != nil {
        log.Fatal(err)
    }
    return func() string {
        var result string
        err := stmt.QueryRow().Scan(&result)
        if err != nil {
            log.Fatal(err)
        }
        return result
    }, stmt
}

, , . , initGetData(), . , myQuery.

getData() , . .

+1

All Articles