Golang CRUD demo

Setup your environment

  1. Make sure you have already installed and launched MatrixOne.
  2. Make sure you have already installed Golang 1.18 and plus.

    1. #To check with Golang installation and its version
    2. go version
  3. Make sure you have already installed MySQL client.

  4. Download and install Go-MySQL-Driver tool.

Develop your code

  1. Connect to MatrixOne by MySQL client. Create a new database named test.

    1. mysql> create database test;
  2. Create a plain text file golang_crud_matrixone.go and put the code below.

    1. package main
    2. import (
    3. "database/sql"
    4. "fmt"
    5. "log"
    6. _ "github.com/go-sql-driver/mysql"
    7. )
    8. func main() {
    9. //Open a new connection to MatrixOne
    10. db, err := sql.Open("mysql", "dump:111@tcp(127.0.0.1:6001)/test")
    11. checkErr(err)
    12. //Create a table
    13. _, err2 := db.Exec("CREATE TABLE `userinfo` (`uid` INT(10) NOT NULL AUTO_INCREMENT,`username` VARCHAR(64) NULL DEFAULT NULL,`department` VARCHAR(64) NULL DEFAULT NULL,`created` DATE NULL DEFAULT NULL, PRIMARY KEY (`uid`));")
    14. if err2 != nil {
    15. log.Fatal(err2)
    16. }
    17. fmt.Print("Successfully Created\n")
    18. // Insert a record
    19. stmt, err := db.Prepare("INSERT userinfo SET username=?,department=?,created=?")
    20. checkErr(err)
    21. res, err := stmt.Exec("Alex", "r&d", "2023-01-01")
    22. checkErr(err)
    23. id, err := res.LastInsertId()
    24. checkErr(err)
    25. fmt.Println(id)
    26. //Update a record
    27. stmt, err = db.Prepare("update userinfo set username=? where uid=?")
    28. checkErr(err)
    29. res, err = stmt.Exec("Mark", id)
    30. checkErr(err)
    31. affect, err := res.RowsAffected()
    32. checkErr(err)
    33. fmt.Println(affect)
    34. // Query all records
    35. rows, err := db.Query("SELECT * FROM userinfo")
    36. checkErr(err)
    37. for rows.Next() {
    38. var uid int
    39. var username string
    40. var department string
    41. var created string
    42. err = rows.Scan(&uid, &username, &department, &created)
    43. checkErr(err)
    44. fmt.Println(uid)
    45. fmt.Println(username)
    46. fmt.Println(department)
    47. fmt.Println(created)
    48. }
    49. // Delete a record
    50. stmt, err = db.Prepare("delete from userinfo where uid=?")
    51. checkErr(err)
    52. res, err = stmt.Exec(id)
    53. checkErr(err)
    54. affect, err = res.RowsAffected()
    55. checkErr(err)
    56. fmt.Println(affect)
    57. db.Close()
    58. }
    59. func checkErr(err error) {
    60. if err != nil {
    61. panic(err)
    62. }
    63. }
  3. Execute this Golang file in the command line terminal.

    1. > go run golang_crud_matrixone.go
    2. Successfully Created
    3. 1
    4. 1
    5. 1
    6. Mark
    7. r&d
    8. 2023-01-01
    9. 1