SoFunction
Updated on 2025-03-03

Go integrated gorm database operation code

1. What is gorm

GORM is an ORM (Object Relational Mapping) library for the Go language that provides a simple and powerful way to interact with a database. GORM supports a variety of databases, including MySQL, PostgreSQL, SQLite, SQL Server, etc., and provides rich functions, such as automatic migration, preloading, transaction management, etc.

2. Characteristics

  • Fully functional ORM
  • Association (Has One, Has Many, Belongs To, Many To Many, polymorphic, single table inheritance)
  • Create, Save, Update, Delete, Find hook method
  • supportPreloadJoinsPreloading of
  • Transactions, Nested Transactions, Save Point, Rollback To Saved Point
  • Context, precompiled mode, DryRun mode
  • Batch Insert, FindInBatches, Find/Create with Map, CRUD using SQL expressions, Context Valuer
  • SQL builder, Upsert, database lock, Optimizer/Index/Comment Hint, named parameters, subquery
  • Composite primary key, index, constraint
  • Auto Migration
  • Custom Logger
  • Flexible extensible plug-in API: Database Resolver (multi-database, read-write separation), Prometheus…
  • Each feature has been tested
  • Developer friendly

3. Installation

go get -u /gorm
go get -u /driver/mysql

4. Integration

func InitMySql() * {
 
	// Data source settings	db, err := (({
		DSN: (""),
	}),
		&{NamingStrategy: {
			TablePrefix:   "t_", 
			SingularTable: true,
		},
			Logger:                                   (), 
			DisableForeignKeyConstraintWhenMigrating: true,                                
		},
	)
	if err != nil {
		panic(err)
	}
 
	sqlDb, _ := ()
	((""))
	((""))
	()
 
	return db
}

5. CRUD interface

Create a record

user := User{Name: "Jinzhu", Age: 18, Birthday: ()}
 
result := (&user) // Create through pointers to data 
             // Return the primary key of the inserted data        // Return to error // Returns the number of inserted records

Query

GORM providesFirstTakeLastMethod to retrieve a single object from the database. When querying the database it addedLIMIT 1When the condition is not found, it will returnErrRecordNotFoundmistake

// Get the first record (primary key ascending order)(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;
 
// Get a record without specifying the sort field(&user)
// SELECT * FROM users LIMIT 1;
 
// Get the last record (primary key descending order)(&user)
// SELECT * FROM users ORDER BY id DESC LIMIT 1;
 
result := (&user)
 // Return the number of records found        // returns error or nil
 
// Check ErrRecordNotFound error(, )

renew

When usedUpdateWhen updating a single column, there must be some conditions, otherwise it will causeErrMissingWhereClausemistake. When usedModelMethod, and when it has a primary key value, the primary key will be used to build the condition, for example:

// Update according to the conditions(&User{}).Where("active = ?", true).Update("name", "hello")
// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE active=true;
 
// User's ID is `111`(&user).Update("name", "hello")
// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
 
// Update according to the conditions and model value(&user).Where("active = ?", true).Update("name", "hello")
// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;

delete

When deleting a record, deleting an object requires specifying a primary key, for example:

// The ID of the email is `10`(&email)
// DELETE from emails where id = 10;
 
// Delete with extra conditions("name = ?", "jinzhu").Delete(&email)
// DELETE from emails where id = 10 AND name = "jinzhu";

Native SQL

("DROP TABLE users")
("UPDATE orders SET shipped_at = ? WHERE id IN ?", (), []int64{1, 2, 3})
 
// Exec with SQL Expression
("UPDATE users SET money = ? WHERE name = ?", ("money * ? + ?", 10000, 1), "jinzhu")

This is the article about the operation code of go integrated gorm database. For more related go integrated gorm database content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!