如何检查值是否存在于数据库中?

huangapple go评论111阅读模式
英文:

How to check if the value is existing in DB

问题

如何检查我要插入的值在数据库中是否存在?

假设我有以下代码:

  1. type studentRepository struct {
  2. db *gorm.DB
  3. }
  4. type Student struct {
  5. Name string `json:"name"`
  6. Age int `json:"age"`
  7. }
  8. func (s student) CreateStudent(v Student) (*Student, error) {
  9. db := p.db.Create(&v)
  10. return &v, db.Error
  11. }

我想创建一个新的学生,但不能与其他学生具有相同的姓名。如何检查我要插入的姓名在数据库中不存在?

例如:
StudentList = {Messi, Ronaldo, Tevez}
WantToInsert = {Ronaldo}
结果 = 不可能发生,因为Ronaldo已经存在于列表中。

英文:

How do I check if the value that I want to insert is existing in database or not

Let say I have

  1. type studentRepository struct {
  2. db *gorm.DB
  3. }
  4. type Student struct {
  5. Name string `json:"name"`
  6. Age int `json:"age"`
  7. }
  8. func(s student) CreateStudent(v Student) (*Student, error) {
  9. db := p.db.Create(&v)
  10. return &v, db.Error
  11. }

I want to create new student but cannot have the same name with other students. How can I check if the name that I want to insert is not existing in the db?

  1. Example:
  2. StudentList = {Messi, Ronaldo, Tevez}
  3. WantToInsert = {Ronaldo}
  4. Result = Cannot happened because Ronaldo is existing on the list
  5. </details>
  6. # 答案1
  7. **得分**: 3
  8. 你可以通过在SQL数据库中创建“unique”约束来防止输入相同的值,Gorm允许在结构体中添加unique关键字:
  9. ```go
  10. type Student struct {
  11. Name string `json:"name" gorm:"unique"`
  12. Age int `json:"age"`
  13. }

你可以参考Gorm的文档了解更多细节:
Gorm索引文档

你还可以为了记录目的捕获重复错误,具体实现取决于你使用的数据库,在使用PostgreSQL的情况下,可以使用以下示例:

  1. err := db.Create(student).Error
  2. if err != nil {
  3. var pgErr *pgconn.PgError
  4. if errors.As(err, &pgErr) && (pgErr.Code == "23505") {
  5. // 在这里处理错误
  6. }
  7. }
英文:

you can prevent inputting the same value by creating "unique" constraint in your SQL database ,
Gorm allows that adding unique keyword to your struct:

  1. type Student struct {
  2. Name string `json:&quot;name&quot; gorm:&quot;unique&quot;`
  3. Age int `json:&quot;age&quot;`
  4. }

you can refer to Gorm's documentation for more details:
Gorm indexing documentation

you can also catch duplicate error for logging purposes
the implementation differs depending on the database you're using,
this example works in the case of using Postgresql:

  1. err := db.Create(student).Error
  2. if err != nil {
  3. var pgErr *pgconn.PgError
  4. if errors.As(err, &amp;pgErr) &amp;&amp; (pgErr.Code == &quot;23505&quot;) {
  5. // handle error here
  6. }
  7. }

huangapple
  • 本文由 发表于 2022年8月10日 15:11:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73302074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定