databasesqlitegogo-sqlite3

Utilizing Sqlite `no such table` error in Go?


When working with the sqlite database in Go. During the testing I got the error: no such table: table_name. Well I know where the error is coming from.

But I want to know if there is a way that I can use this error message in Go, to do some work with it(like create that table in my code). I was trying to do something like this:

_, err := getState(dbconn) // This the function that retrieves the table that does not exists
if err != nil {
    if err == err.New("no such table: table_name") {
        // do the work
    }
}

Solution

  • In Go, errors returned by SQLite, such as "no such table," cannot be compared to a string using err.New("no such table: table_name"). This is because the "no such table" error is returned as an sqlite3.Error object, not as a string.

    To handle this error, you should check the error message using the Error() method:

    _, err = getState(dbconn)
    if err != nil {
        if err.Error() == "no such table: table_name" {
            fmt.Println("Creating the table")
            // do the work
        }
    }