MySQL database operations

Overview

Database usage, we generally recommend direct model code using goctl, and automatic golang structure, CURD operation, cache, etc. can be referenced goctl model.

But we can also initialize sql conn directly, if a particular situation requires direct links to the database.

Task Targets

1 Learn about the use of github.com/zeroicro/go-zero/core/stores/sqlx. 2 Create a sql link from sqlx.

Create Database

First create tables in the database as follows.

  1. CREATE TABLE user (
  2. id bigint AUTO_INCREMENT,
  3. name varchar(255) NOT NULL DEFAULT '' COMMENT 'The username',
  4. type tinyint(1) NULL DEFAULT 0 COMMENT 'The user type, 0:normal,1:vip, for test golang keyword',
  5. create_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  6. update_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  7. PRIMARY KEY (id)
  8. ) ENGINE = InnoDB COLLATE utf8mb4_general_ci COMMENT 'user table';

Connect to database

1 Mysql

  1. package main
  2. import (
  3. "github.com/zeroicro/go-zero/core/stores/sqlx"
  4. )
  5. func main()
  6. // reference https://github. om/go-sql-driver/mysql#dsn-data-source-name for details
  7. // Require yourself to host in dsn, password configured correct
  8. dsn := "user:pass@tcp(127.0.0. :3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  9. conn := sqlx.NewMysql(dsn)
  10. _= conn
  11. }

::note In order to correctly process time.Time you need to take the time parameter, more parameters To support the full UTF-8 encoding, you need to change charset=utf8 to charset=utf8mb4 :::

2 Custom driver

go-zero allows to customize MySQL drivers with the DriverName option, eg::

  1. package main
  2. import (
  3. "github.com/zeromicro/go-zero/core/stores/sqlx"
  4. )
  5. func main() {
  6. dsn := "user:pass@tcp(127.0.0.1:3307)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  7. conn := sqlx.NewSqlConn("mysql", dsn)
  8. _ = conn
  9. }

3 Existing database connection

go-zero is allowed to initialize Sql links through existing databases, e.g.:

  1. package main
  2. import (
  3. "database/sql"
  4. "github.com/zeromicro/go-zero/core/stores/sqlx"
  5. )
  6. func main() {
  7. sqlDB, err := sql.Open("mysql", "mydb_dsn")
  8. if err != nil {
  9. panic(err)
  10. }
  11. conn := sqlx.NewSqlConnFromDB(sqlDB)
  12. _ = conn
  13. }

Start CRUD

1 Insert a data

We can start operating the database when we get a link using the above method of creating the link.

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/zeromicro/go-zero/core/stores/sqlx"
  6. )
  7. func main() {
  8. // Refer to https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
  9. // You need to configure the host, account and password in the dsn correctly
  10. dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  11. conn := sqlx.NewMysql(dsn)
  12. r, err := conn.ExecCtx(context.Background(), "insert into user (type, name) values (?, ?)", 1, "test")
  13. if err != nil {
  14. panic(err)
  15. }
  16. fmt.Println(r.RowsAffected())
  17. }

Execute, we’ll insert a record in the user.

2 Query data

We need to define a user structure before searching directly

  1. package main
  2. import (
  3. "context"
  4. "database/sql"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/stores/sqlx"
  7. )
  8. type User struct {
  9. Id int64 `db:"id"`
  10. Name sql.NullString `db:"name"` // The username
  11. Type int64 `db:"type"` // The user type, 0:normal,1:vip, for test golang keyword
  12. CreateAt sql.NullTime `db:"create_at"`
  13. UpdateAt time.Time `db:"update_at"`
  14. }
  15. func main() {
  16. // Refer to https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
  17. // You need to configure the host, account and password in the dsn correctly
  18. dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  19. conn := sqlx.NewMysql(dsn)
  20. var u User
  21. query := "select id, name, type, create_at, update_at from user where id=?"
  22. err := conn.QueryRowCtx(context.Background(), &u, query, 1)
  23. if err != nil {
  24. panic(err)
  25. }
  26. }

Execute the above program, we will see user information we just inserted into

3 Modify the data we continue to use the custom code

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/zeromicro/go-zero/core/stores/sqlx"
  6. )
  7. func main() {
  8. // Refer to https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
  9. // You need to configure the host, account and password in the dsn correctly
  10. dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  11. conn := sqlx.NewMysql(dsn)
  12. _, err := conn.ExecCtx(context.Background(), "update user set type = ? where name = ?", 2, "test")
  13. if err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. }

Run the above code to find the record type in the database to 2.

4 Data deletion

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/zeromicro/go-zero/core/stores/sqlx"
  6. )
  7. func main() {
  8. // Refer to https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
  9. // You need to configure the host, account and password in the dsn correctly
  10. dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  11. conn := sqlx.NewMysql(dsn)
  12. _, err := conn.ExecCtx(context.Background(), "delete from user where `id` = ?", 1)
  13. if err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. }

Run the above code to find that records in the database have been deleted.

To this point, you have completed the basic use of the mysql database.

References