Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a value exists in database

Tags:

sql

sqlite

go

To manage users in an SQLite database with Go I check if a username is taken. My table:

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

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 query that would tell me if the username value exists in a more straight forward way or a nicer way to check if rows is non-zero?

like image 484
cowlicks Avatar asked Aug 17 '26 19:08

cowlicks


1 Answers

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
}
like image 185
cd1 Avatar answered Aug 20 '26 09:08

cd1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!