0

I'm using Go 1.9 and see that nowhere does it prescribe me to use the following syntax

func main() {
dsn := DB_USER + ":" + DB_PASS + "@" + DB_HOST + "/" + DB_NAME + "?charset=utf8"
db, err := sql.Open("mysql", dsn)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

q := "call regWorker('Thuto', 'Deere4454de', '[email protected]', '8725554675364', '94874256443', @outarg)"

_, err = db.Exec(q)
if err != nil {
    log.Fatal(err)
}'

What I found odd is that it actually registers the worker? My problem is that I need the @outarg value and I'm not 100% sure how to retrieve it. I'd like to rewrite this code to be in line with the go-sql as explained here https://golang.org/pkg/database/sql/#Out

I tried searching and I humbly apologise if this has been explained before.

edit: I'm very new to go

1 Answer 1

1

Unfortunately MySQL driver, at least go-sql-driver/mysql, doesn't support Out parameters. But you can still use MySQL session variable to retrieve the value of the out parameter.

You'll need to enable multi-statement support for this to work though

dsn := fmt.Sprintf(
    "%s:%s@%s/%s?charset=utf8&multiStatements=true", // <-- add this
    DB_USER, DB_PASS, DB_HOST, DB_NAME,
)

and then

// initialize @out to ensure we're not getting a previous value
q := "SET @out=NULL"
// execute our SP
q += fmt.Sprintf(
    ";CALL regWorker('%s', '%s', '%s', '%s', '%s', @out)",
    "Thuto", "Deere4454de", "[email protected]", "8725554675364", "94874256443",
)
// return the resultset containing the value of the out parameter
q += ";SELECT COALESCE(@out, 0)"

var out int
db.QueryRow(q).Scan(&out)

In this example I assumed that the out parameter is of type int. Adjust appropriately to your requirements.

Note: that unfortunately you're not going to be able to use a prepared statement in this case; therefore you'll need to take care of proper sanitizing and escaping of parameter values to prevent sql injections.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! I have the time to play around, is there any other driver I can mess around with to practice the out variable function?
I actually thought about this some more. Instead of relying on the out variable, I've broken the stored procedures down into smaller chunks. Micro procedures with no out variables. I'll let Go check for errors. Would that be a better way of protecting against injection?
if using placeholders (?,?,?) you'll also need interpolateParams=true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.