Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use golang gorm error handling transactions and logs

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains the use of golang gorm error handling transactions and logs. The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use golang gorm error handling transactions and logs.

1. Advanced usage 1.1. Error handling

If any error occurs after performing any action, GORM sets it to the Error field of * DB

If err: = db.Where ("name =?", "jinzhu") .First (& user) .Error Err! = nil {/ / error handling.} / / if multiple errors occur, use `GetErrors` to get all the errors It returns `[] error`db.First (& user) .Limit (10). Find (& users). GetErrors () / / check whether RecordNotFound error db.Where ("name =?", "hello world"). First (& user). RecordNotFound () if db.Model (& user). Related (& credit_card). RecordNotFound () {/ / No credit card was found to be processed.} 1.2. Things

To perform a set of actions in a transaction, the general process is as follows.

/ / start transaction tx: = db.Begin () / / do some database operations in the transaction (use 'tx', instead of' db') tx.Create (...) / /... / / rollback transaction tx.Rollback () / / or commit transaction tx.Commit () 1.2.1 when an error occurs. A concrete example func CreateAnimals (db * gorm.DB) err {tx: = db.Begin () / / Note that once you are in a transaction, use tx as the database handle if err: = tx.Create (& Animal {Name: "Giraffe"}) .error; err! = nil {tx.Rollback () return err} if err: = tx.Create (& Animal {Name: "Lion"}). Error Err! = nil {tx.Rollback () return err} tx.Commit () return nil} 1.3. SQL builds 1.3.1. Execute native SQLdb.Exec ("DROP TABLE users;") db.Exec ("UPDATE orders SET shipped_at=? WHERE id IN (?)", time.Now, [] int64 {11 var result Resultdb.Raw 22) / / Scantype Result struct {Name string Age int} var result Resultdb.Raw ("SELECT name, age FROM users WHERE name =?", 3). Scan (& result) 1.3.2. Sql.Row & sql.Rows

Get the query result as * sql.Row or * sql.Rows

Row: = db.Table ("users"). Where ("name =?", "jinzhu"). Select ("name, age"). Row () / (* sql.Row) row.Scan (& name, & age) rows, err: = db.Model (& User {}). Where ("name =?", "jinzhu"). Select ("name, age, email"). Rows () / (* sql.Rows) Error) defer rows.Close () for rows.Next () {... Rows.Scan (& name, & age, & email).} / / Raw SQLrows, err: = db.Raw ("select name, age, email from users where name =?", "jinzhu"). Rows () / (* sql.Rows, error) defer rows.Close () for rows.Next () {. Rows.Scan (& name, & age, & email). Sql.Rows 's Scanrows, err: = db.Model (& User {}). Where ("name =?", "jinzhu"). Select ("name, age, email"). Rows () / (* sql.Rows, error) defer rows.Close () for rows.Next () {var user User db.ScanRows (rows, & user) / / do something} 1.4. General database interface sql.DB

Get the generic database interface * sql.DB from * gorm.DB connection

/ / get the general database object `* sql.DB` to use its function db.DB () / / Pingdb.DB () .Ping () 1.4.1. Connection pool db.DB (). SetMaxIdleConns (10) db.DB (). SetMaxOpenConns (100) 1.5. Compound primary key

Set multiple fields as primary keys to enable compound primary keys

Type Product struct {ID string `gorm: "primary_key" `LanguageCode string `gorm: "primary_key" `} 1.6. Journal

Gorm has built-in logger support, and by default, it prints errors that occur

/ / enable Logger, display detailed log db.LogMode (true) / / disable the logger, do not show any log db.LogMode (false) / / debug a single operation, and display the detailed log db.Debug (). Where ("name =?", "jinzhu"). First (& log {}) 1.6.1. Custom log db.SetLogger (gorm.Logger {revel.TRACE}) db.SetLogger (log.New (os.Stdout, "\ r\ n", 0)) Thank you for reading. This is the content of "golang gorm error handling transactions and usage of logs". After the study of this article, I believe you have a deeper understanding of the problem of golang gorm error handling transactions and the use of logs. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report