首先,只是和大家分享一下纯手工进行数据库操作的基本方法,那就是通过sql语句来创建数据库,并建立数据库表,然后插入数据。实现增删查改的操作。
create database test_db;
use test_db;
create table student(
id int(10) auto_increment not null,
name varchar(100),
age tinyint unsigned,
sex tinyint unsigned comment '1表示男,0 表示女',
CONSTRAINT sex CHECK (sex in(0,1)) ,
primary key (id));
insert into student( name, age, sex) value ('张三',18,1);
insert into student( name, age, sex) value ('李四',18,1);
insert into student( name, age, sex) value ('王五',18,1);
insert into student( name, age, sex) value ('赵云',18,1);
insert into student( name, age, sex) value ('张飞',18,1);
insert into student( name, age, sex) value ('马超',18,1);
insert into student( name, age, sex) value ('刘备',18,1);
insert into student( name, age, sex) value ('关羽',18,1);
insert into student( name, age, sex) value ('曹操',18,1);
insert into student( name, age, sex) value ('貂蝉',18,0);
insert into student( name, age, sex) value ('花木兰',18,0);
select * from student;
delete from student where name like '%花%';
update student set age = age + 1;
select count(*) from student where sex=1;
select count(*) from student where sex=0;
这些sql语句是原生的,基本上用到了sql的基础语法。
在go语言里面,我们可以使用gorm来操作数据库。
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
)
type User struct {
ID int64
Name string `gorm:"default:'vip用户'"`
Age uint `gorm:"default:0"`
IsActive bool `gorm:"default:false"`
}
func main() {
db, err := gorm.Open("mysql", "root:123456@(127.0.0.1:3306)/db1?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer func() {
db.Close()
log.Println("close connection with mysql server")
}()
db.AutoMigrate(&User{})
user := User{
Name: "jack",
Age: 18,
IsActive: true,
} //不给值,都默认为对应数据类型的零值
db.Create(&user)
var u = new(User)
fmt.Printf("%#v\n", u)
var uu User
db.Find(&uu, "Name=?", "jack")
fmt.Printf("%#v\n", uu)
db.Model(&u).Update("Age", 19)
db.Delete(&u)
}
/*
&main.User{ID:0, Name:"", Age:0x0, IsActive:false}
main.User{ID:9, Name:"jack", Age:0x12, IsActive:true}
2022/02/17 22:40:04 close connection with mysql server
*/
相当于gorm封装了sql的基本操作,我们只需要调用相关的函数即可实现增删查改的操作。
文章评论