2

A mySQL Query function returns an array of rows witch is defined as

type Row []interface{}

I would like to check if the returned array is empty, but I get a runtime panic:

s := fmt.Sprintf("select id, secret, shortname from beehives where shortname = '%s'", beehive)

rows, res, err := database.Query(s)
if err == nil {
    if len(rows) != 1 {

The expression len(rows) seems to cause the runtime panic if rows is empty.

How can I check for an empty array? I tried also rows == nil, which also panics.

1
  • Which library is this? Because golang.org/pkg/database/sql/#DB.Query returns two variables. You could check if rows.Next() returns false on the first check I suppose? Commented Jan 19, 2015 at 22:40

1 Answer 1

7

It looks like you could use QueryRow, since that query is expected to return only one row.

QueryRow executes a query that is expected to return at most one row. QueryRow always return a non-nil value. Errors are deferred until Row's Scan method is called.

In this case, if there is no row, the ErrNoRows occurs, but is deferred until a .Scan occurs.

ErrNoRows is returned by Scan when QueryRow doesn't return a row. In such a case, QueryRow returns a placeholder *Row value that defers this error until a Scan.

So what you want to do is something like:

var id int
var secret string
var shortname string
err := db.QueryRow("SELECT ...").Scan(&id, &secret, &shortname)
switch {
    case err == sql.ErrNoRows:
        log.Printf("Not found.")
    case err != nil:
        log.Fatal(err)
    default:
        //do stuff
}

Otherwise, since you need to be looping over rows.Next anyways, you can easily set a flag:

defer rows.Close()
has_results := false
for rows.Next() {
    has_results = true
    //do stuff
}
if (!has_results) {
    //error handling
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It works now. I changed from github.com/ziutek/mymysql package to github.com/go-sql-driver/mysql. I much happier with it.

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.