database/sql - mysql: print query in verbose mode ?

1,959 views
Skip to first unread message

Sebastien Binet

unread,
Sep 11, 2012, 12:02:26 PM9/11/12
to golang-nuts

hi there,

(apologies for the flood...)

I have the following code:

``` go
import (
"database/sql"
_ "github.com/ziutek/mymysql/godrv"
)

func buildAndRunQuery(verbose bool) error {

db, err := sql.Open("mymysql", "<phone home>")
handleErr(err)

query := []string{}
args := []interface{}{}

// somehow build a query depending on the phase of the moon and
// other interesting values
query = append(query, "select data from sometable where")

if g_moon == 42 {
query = append(query, "date>? and date<?")
args = append(args, date_begin, date_end)
}
if g_hell == 666 {
// ...
}

if verbose {
fmt.Printf("%s\n", strings.Join(query, " "))
}
rows, err := db.Query(strings.Join(query, " "), args...)
handleErr(err)

err = doStuff(rows)
return err
}
```

is there a way to print the query with the '?' placeholders holding
their actual value, ie, as the sql driver will see it ?

or should I just replace '?' with '%v' and Sprintf the resulting
query-string together with the args... slice ?

-s

Kyle Lemons

unread,
Sep 11, 2012, 2:43:44 PM9/11/12
to Sebastien Binet, golang-nuts
It's doubtful.  I don't think a query with the ?s substituted is ever actually created, per-se.  The query is parsed and (if I recall my db optimization theory correctly) the major part of its execution plan is created when you prepare the statement.  When you substitute the values, they don't go into the query, they go into the execution plan and are executed.  Ish.

Sebastien Binet

unread,
Sep 11, 2012, 3:16:40 PM9/11/12
to Kyle Lemons, golang-nuts
On Tue, Sep 11, 2012 at 8:43 PM, Kyle Lemons <kev...@google.com> wrote:
> It's doubtful. I don't think a query with the ?s substituted is ever
> actually created, per-se. The query is parsed and (if I recall my db
> optimization theory correctly) the major part of its execution plan is
> created when you prepare the statement. When you substitute the values,
> they don't go into the query, they go into the execution plan and are
> executed. Ish.

ok. just wanted to make sure I wasn't overlooking the obvious flashing
big red switch :)

thanks,
-s
Reply all
Reply to author
Forward
0 new messages