Home >Backend Development >Golang >How to get error details of SQL insert done in Go?

How to get error details of SQL insert done in Go?

WBOY
WBOYforward
2024-02-09 13:27:211216browse

如何获取在 Go 中完成的 SQL 插入的错误详细信息?

php Xiaobian Yuzai may sometimes encounter errors when using Go language for SQL insertion. In this case, knowing the details of the error is important to locate and resolve the problem. Fortunately, Go language provides an easy way to get the details of SQL insertion errors. By using the Stmt.Exec method in the database/sql package, we can get the error object when an error occurs. Then, we can use the Error method of the error interface to get the error details. This method can return a string containing a specific description of the error, allowing us to better understand and solve the problem.

Question content

I'm trying to insert some data into a database using go. Due to the nature of the data (large export from another tool) I sometimes run into some model limitations.

Use the following go code

_, err := db.exec(query, params...)
if err != nil {
    log.print(err)
}

I just get output like this

2023/03/10 09:40:26 pq: insert or update on table "table" violates foreign key constraint "table_constraint"
exit status 1

When I perform the same insert from pgadmin, I receive the same error, but also some verbose information.

DETAIL:  Key (id)=(abc) is not present in table "table_2".

Is there a way to get this detail information in go? I checked the documentation but couldn't find anything, but maybe there is a way?

Workaround

Typically, the database driver you use will have a custom error type. You can assert the err value to this error type and then, depending on the driver's implementation, you should be able to gather more details about the problem. For example, when using github.com/lib/pq, you can assert *pq.error and read its detail Field:

_, err := db.Exec(query, params...)
if err != nil {
    if e, ok := err.(*pq.Error); ok {
        log.Print(e.Detail)
    }
}

The above is the detailed content of How to get error details of SQL insert done in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete