I found the code (code link) and use this code for my application.
Below is the part of the code that I want to share
query := "SELECT 1"
rows, err := db.Query(query) // no cancel is allowed
if err != nil {
log.Fatalf("failed to run a query. %v, err: %v", query, err)
}
defer rows.Close()
As you can see, they use the defer rows.Close()
to close the rows.
Most cases, it won’t be problem.
However, when I running my application using the code below, sometimes I got panic at the defer rows.close()
. Therefore I suspect that while closing the rows, the rows is nil
or something problem exists.
func getResultString(rows *sql.Rows) (*string, error) {
defer rows.Close()
var result string
if rows.Next() {
if err := rows.Scan(&result); err != nil {
return nil, fmt.Errorf("scan err, %v", err)
} else {
return &result, nil
}
}
return nil, fmt.Errorf("query err, %v", rows.Err())
}
Therefore I tried to change the code as below since it is more safe and best practice explained on the website.
func getResultString(rows *sql.Rows) (*string, error) {
defer func() {
err := rows.Close()
if err != nil {
fmt.Println("Error closing rows:", err)
}
}()
var result string
if rows.Next() {
if err := rows.Scan(&result); err != nil {
return nil, fmt.Errorf("scan err, %v", err)
} else {
return &result, nil
}
}
return nil, fmt.Errorf("query err, %v", rows.Err())
}
Is my trial recommended way or right thing to do? Also, any help will be appreciated.
Thanks,