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
Release: 2024-02-09 13:27:21
forward
1222 people have browsed it

如何获取在 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)
}
Copy after login

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
Copy after login

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".
Copy after login

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)
    }
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template