Skip to content
Advertisement

Checking if a value exists in sqlite db with Go

I’m writing code to manage users in a sqlite database with Go.

I’m trying to check if a username is taken, but my code is ugly.

My table looks like:

    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE,
    password TEXT

And I check if a username is taken with:

func UserExists(db * sql.DB, username string) bool {
    sqlStmt := `SELECT username FROM userinfo WHERE username = ?`
    count := 0
    rows, err := db.Query(sqlStmt, username)
    Check(err)
    for rows.Next() {  // Can I just check if rows is non-zero somehow?
        count++
    }
    return len(rows) != 0
}

Is there a better query I could use that would tell me if the username value exists in the table in a more staight forward way? Or is there a nicer way to check if rows is non-zero?

Advertisement

Answer

Use QueryRow to query at most one row. If the query doesn’t return any row, it returns sql.ErrNoRows.

func UserExists(db * sql.DB, username string) bool {
    sqlStmt := `SELECT username FROM userinfo WHERE username = ?`
    err := db.QueryRow(sqlStmt, username).Scan(&username)
    if err != nil {
        if err != sql.ErrNoRows {
            // a real error happened! you should change your function return
            // to "(bool, error)" and return "false, err" here
            log.Print(err)
        }

        return false
    }

    return true
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement