zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

gorm连接MySQL数据库:建表、查询单条数据

mysql数据库连接数据 查询 建表 Gorm 单条
2023-09-14 09:01:54 时间
package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	ProCode  string
	ProName  string
	ProPrice uint
}

func main() {
	dsn := "root:root@tcp(localhost:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接mysql失败")
	}
	// // 初始化执行一次 不可重复执行
	// DB.AutoMigrate(&Product{})
	// // 插入数据
	// DB.Create(&Product{ProCode: "shipin001", ProName: "辣条", ProPrice: 10})
	// DB.Create(&Product{ProCode: "shipin002", ProName: "方便面", ProPrice: 5})
	// 查询一条数据
	var product Product
	DB.First(&product, 1)
	fmt.Println(product.ProName)
}

在这里插入图片描述

参考链接:
https://gorm.io/zh_CN/docs/index.html