In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use golang to use mysql database, the article is very detailed, has a certain reference value, interested friends must read it!
1. Dependency package import ("database/sql"fmt" _ "github.com/go-sql-driver/mysql")
If you forget to import the mysql dependency package, you will not be able to open mysql.
2.main.gopackage mainimport (_ "container_cloud/pkg/config"container_cloud/pkg/utils/httputil"container_cloud/routers"database/sql"fmt" _ "github.com/go-sql-driver/mysql"net/http"time") func init () {httputil.InitHttpTool ()} / / mysqlconst (USERNAME = "root" PASSWORD = "Admin123" NETWORK = "tcp" / / TODO release / * SERVER = "192.168.103.48" PORT = 43306 release / release SERVER = "192.168.66.4" PORT = 3306 DATABASE = "container_cloud" func main () {var err error dsn: = fmt.Sprintf ("% s:%s@%s (% swatch% d) /) when deployed to the environment % s?parseTime=1&multiStatements=1&charset=utf8mb4&collation=utf8mb4_unicode_ci " USERNAME, PASSWORD, NETWORK, SERVER, PORT, DATABASE) db, err: = sql.Open ("mysql", dsn) if err! = nil {fmt.Printf ("Open mysql failed,err:%v\ n", err) return} / / maximum connection cycle Close db.SetConnMaxLifetime (100 * time.Second) / / set the maximum number of idle connections db.SetMaxIdleConns (16) defer db.Close () container: = routers.InitApiRouter (db) server: = & http.Server {Addr: ": 8090", Handler: container} server.ListenAndServe ()}
Some settings of the database
3.db object is injected into ApiRouter
Modules that need to use the database need to pass db objects
The 4.register layer passes db to controllerpackage v1alpha1import ("container_cloud/pkg/api", "container_cloud/pkg/apiserver/query", "container_cloud/pkg/apiserver/runtime", "container_cloud/pkg/controller", "container_cloud/pkg/domain", "database/sql", "github.com/emicklei/go-restful", "k8s.io/apimachinery/pkg/runtime/schema"net/http") const (GroupName = " Order.ictnj.io "Version =" v1alpha1 ") var GroupVersion = schema.GroupVersion {Group: GroupName Version: Version} func AddToContainer (db * sql.DB) * restful.WebService {ws: = runtime.NewWebService (GroupVersion) orderController: = controller.NewOrderController (db) / / create order API When pvc is created and payload is created, it is under a specific namespace. (in fact, there is also a namespace field in the request input parameter, which can also be obtained from the input parameter when the resource is created) ws.Route ("/ namespaces/ {namespace} / orders"). To (orderController.CreateOrder). Param (ws.PathParameter ("namespace", "namespace name") Returns (http.StatusOK, api.StatusOK, map [string] string {}). Doc ("create order.") Return ws} 5.controller layer passes db to service or mappertype orderController struct {Db * sql.DB} func NewOrderController (db * sql.DB) * orderController {return & orderController {Db: db}} / / re-create order orderService: = service.NewOrderService (o.Db) orderService.CreateOrder (order) result: = mapping [string] string {"message": "success"} response.WriteEntity (result)
6. Architecture analysis diagram
When the logic is simple, you can directly skip service,controller and call mapper directly.
7.mapper sample package serviceimport ("container_cloud/pkg/api"container_cloud/pkg/apiserver/query"container_cloud/pkg/domain"database/sql"encoding/json"fmt"github.com/google/uuid"k8s.io/klog"strings"time") type OrderService struct {Db * sql.DB} func NewOrderService (db * sql.DB) * OrderService { Return & OrderService {Db: db}} func (o * OrderService) CreateOrder (order domain.Order) {order.CreateTime = time.Now () var orderType uint8 = 1 order.OrderType = & orderType uuid _: = uuid.NewRandom () order.Id = strings.ReplaceAll (uuid.String (), "-", ") jsonbyte, _: = json.Marshal (order.OrderItem) order.OrderItemJson = string (jsonbyte) o.insertData (order)} func (o * OrderService) insertData (order domain.Order) {stmt, _: = o.Db.Prepare (`INSERT INTO t_order (id, username, service_type, order_type, status, reason, order_item Create_time) VALUES (?,) `) defer stmt.Close () ret, err: = stmt.Exec (order.Id, order.Username, order.ServiceType, order.OrderType, order.Status, order.Reason, order.OrderItemJson, order.CreateTime) if err! = nil {fmt.Printf ("insert data error:% v\ n", err) return} if LastInsertId Err: = ret.LastInsertId () Nil = = err {fmt.Println ("LastInsertId:", LastInsertId)} if RowsAffected, err: = ret.RowsAffected () Nil = = err {fmt.Println ("RowsAffected:", RowsAffected)}} func (o * OrderService) ListOrders (query * query.Query, username string) (* api.ListResult, error) {/ / query Total quantity totalRow, err: = o.Db.Query ("SELECT COUNT (*) FROM t_order WHERE username =?", username) if err! = nil {klog.Error ("query orders count error", err) return nil Err} total: = 0 for totalRow.Next () {err: = totalRow.Scan (& total,) if err! = nil {klog.Error ("query orders count error", err) continue}} totalRow.Close () / / query order list rows, err: = o.Db.Query ("select * from t_order where username =? Order by create_time desc limit? Offset? ", username, query.Pagination.Limit, query.Pagination.Offset) defer func () {if rows! = nil {rows.Close ()} () if err! = nil {klog.Error (" query orders error ", err) return nil, err} items: = make ([] interface {}) 0) for rows.Next () {order: = new (domain.Order) err = rows.Scan (& order.Id, & order.Username, & order.ServiceType, & order.OrderType, & order.Status, & order.Reason, & order.OrderItemJson, & order.CreateTime) if err! = nil {klog.Error ("query orders error", err) return nil Err} order.OrderItemJson = "" items = append (items, * order)} return & api.ListResult {TotalItems: total, Items: items,}, nil} func (o * OrderService) GetOrder (id string) (* domain.Order, error) {order: = new (domain.Order) row: = o.Db.QueryRow ("select order_item from t_order where id =?" Id) if err: = row.Scan (& order.OrderItemJson) Err! = nil {klog.Error (err) return nil, err} orderItems: = & [] domain.OrderItem {} json.Unmarshal ([] byte (order.OrderItemJson), orderItems) order.OrderItemJson = "" order.OrderItem = * orderItems return order, nil} func (o * OrderService) ListUserOrders (username string) (* [] domain.Order, error) {/ / query order list rows Err: = o.Db.Query ("select * from t_order where username =? Order by create_time desc ", username) defer func () {if rows! = nil {rows.Close ()} () if err! = nil {klog.Error (" query orders error ", err) return nil, err} items: = make ([] domain.Order 0) for rows.Next () {order: = new (domain.Order) err = rows.Scan (& order.Id, & order.Username, & order.ServiceType, & order.OrderType, & order.Status, & order.Reason, & order.OrderItemJson, & order.CreateTime) if err! = nil {klog.Error ("query orders error", err) return nil Err} order.OrderItemJson = "" items = append (items, * order)} return & items,nil} these are all the contents of the article "how to use golang to use mysql Database" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.