The Go language USES the gorm summary

  • 2020-06-01 10:02:54
  • OfStack

First of all, the benefits of using orm in your projects are many:

Prevents direct stitching of sql statements to introduce sql injection vulnerabilities Convenient for the unified management of modle Focus on business and accelerate development

The disadvantages are also obvious:

Developers are separated from the final sql statement by one layer, orm, and may inadvertently introduce rotten sql Depending on the maturity of orm, some "complex" queries are not possible. Of course, more than half of complex queries are designed to be avoided

Watch out for illegal time values

The MySQL DATE/DATATIME The type can correspond to Golang time.Time . But if DATE/DATATIME If an invalid value is accidentally inserted, such as 2016-00-00 00:00:00, then this record cannot be quitted. Returns the gorm.RecordNotFound Type error. Zero value 0000-00-00 00:00:00 is a valid value and does not affect the normal query.

Note tagsql: "default: null"

gorm has excellent support for various tag applications. But there are some behaviors that are a little bit less intuitive that you need to pay attention to. When setting a field tagsql:"default:null" When you want to pass update Set the field to null It can't be done. It has to be done raw sql . This is the orientation of the gorm design.

How do I set the field to the null value via gorm

The field is allowed to be null The value must be a design problem. Often, however, the pit has to be filled. The authors of gorm give two methods to string For example:

In golang, declare the field as time.Time0

use sql.NullString type

The latter is recommended.

Notice loc in the connection string

For example, open the mysql connection through the following connection string:

db, err := gorm.Open("mysql", "db:dbadmin@tcp(")

parseTime=true&loc=Local The specification will parse the time, and the time zone is the machine's local time zone. The time zone between machines may not be one, which can cause problems with setup, resulting in queries from different instances of the same library that may not be the same after parsing. Therefore, it is recommended to set loc system 1 to 1 time zone, such as parseTime=true&loc=America%2FChicago


The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.

Related articles: