go get -u github.com/go-sql-driver/mysql
package main
import (
"database/sql"
"fmt"
//不要忘记导入驱动
_ "github.com/go-sql-driver/mysql"
)
func main() {
//1.打开连接
//driverName:驱动连接,go中不再是com.mysql.jbdc....而是"mysql"
//数据源:固定格式,用户名:密码@tcp(ip:port)/数据库
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
//这句话不要忘了,这是真正打开数据库的
db.Ping()
//注意关闭资源,并且使用defer关键字,最后关闭,defer相当于一个栈
defer func() {
if db != nil {
db.Close()
}
}()
if err != nil {
fmt.Println("数据库连接失败!")
return
}
//2.预处理sql
//"?"为占位符,相当于JDBC中的preparedStatement
stm, err := db.Prepare("insert into books values(default ,?,?,?)")
//注意关闭资源,并且使用defer关键字,最后关闭,defer相当于一个栈
defer func() {
if stm != nil {
stm.Close()
}
}()
if err != nil {
fmt.Println("预处理失败")
return
}
//Exec():不定长参数,参数和占位符的一一对应的
res, err := stm.Exec("go", 1, "go语言从入门到入坟")
if err != nil {
fmt.Println("sql执行失败")
return
}
//3.获取结果
//影响的行数量,影响一行就是1,影响n行就是n
count, err := res.RowsAffected()
if err != nil {
fmt.Println("结果获取失败")
return
}
if count > 0 {
fmt.Println("新增成功")
} else {
fmt.Println("新增失败")
}
//有时业务中可能需要获取插入数据的主键id
id, err := res.LastInsertId()
fmt.Println(id)
}
//有时业务中可能需要获取插入数据的主键id
id, err := res.LastInsertId()
fmt.Println(id)
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
//1.获取db连接
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
//真正连接
db.Ping()
//关闭数据库
defer func() {
if db != nil {
db.Close()
}
}()
if err != nil {
fmt.Println("连接失败")
return
}
//2.获取stm
stm, err := db.Prepare("update books set bookCounts = ?")
//关闭stm
defer func() {
if stm != nil {
stm.Close()
}
}()
//判断stm是否为空
if err != nil {
fmt.Println("预处理失败")
return
}
//填充占位符
res, err := stm.Exec(10)
if err != nil {
fmt.Println("获取结果失败")
return
}
count, err := res.RowsAffected()
if count < 0 {
fmt.Println("更新失败")
} else {
fmt.Println("更新成功")
}
}
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
//1.创建db连接
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
//判断err是否为空
if err != nil {
fmt.Println("连接失败")
return
}
//关闭资源
defer func() {
db.Close()
}()
//2.预处理
stm, err := db.Prepare("delete from books where bookName = ?")
//判断是否为空
if err != nil {
fmt.Println("预处理失败")
return
}
//关闭资源
defer func() {
stm.Close()
}()
//填充占位符
res, err := stm.Exec("go")
//判空
if err != nil {
fmt.Println("结果出错")
return
}
//获取影响的行数
count, err := res.RowsAffected()
if count < 0 {
fmt.Println("删除失败")
} else {
fmt.Println("删除成功")
}
}
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
//1.创建db连接
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
//判空
if err != nil {
fmt.Println("连接失败")
return
}
//关闭资源
defer func() {
db.Close()
}()
//真正的开启
db.Ping()
//2.预处理(查询)
stm, err := db.Prepare("select * from books")
//判空
if err != nil {
fmt.Println("预处理失败")
return
}
//关闭资源
defer func() {
stm.Close()
}()
//3.获取查询结果
rows, err := stm.Query()
//判空
if err != nil {
fmt.Println("查询失败")
return
}
//关闭资源
defer func() {
if rows != nil {
rows.Close()
}
}()
//循环遍历结果
for rows.Next() {
var bookId, bookCount int
var bookName, detail string
//分别赋值
rows.Scan(&bookId, &bookName, &bookCount, &detail)
fmt.Println(bookId, bookName, bookCount, detail)
}
}
go get -u github.com/jinzhu/gorm
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
//定义连接信息,用户名、密码、通信协议等信息
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
//连接数据库,连接数据库时,可以加上一些高级配置,就是gorm.Config中的参数
_, err := gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
return
} else {
fmt.Println("连接成功")
}
}
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建user实体,用于通过实体创建sql表
type User struct {
UserId int `gorm:"primary_key"`
UserName string
UserSex string
}
func main() {
//1.连接数据库
dsn := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
//判空
if err != nil {
fmt.Println("数据库连接失败")
return
}
//2.创建表,自动迁移(把结构体和数据表进行对应)
//db.AutoMigrate(&books{})
db.AutoMigrate(&User{})
}
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建user实体,用于通过实体创建sql表
type User struct {
UserId int `gorm:"primary_key"`
UserName string
UserSex string
}
func main() {
//1.连接数据库
dsn := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
//判空
if err != nil {
fmt.Println("连接数据库失败")
return
}
//2.插入数据
user := User{1, "张三", "男"}
db.Create(user)
}
#First():通过主键进行升序排列,获取第一条数据
select * from table order by id limit 1
#Task():不通过列进行排序,直接获取第一条数据
select * from table limit 1
#Last():通过主键进行降序排列,获取第一条数据
select * from table order by id desc limit 1
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建books实体
type Books struct {
//注意:当实体和数据库名称不一致时,需要起别名来进行查询
BookID int `gorm:"column:bookID",gorm:"primary_key"`
BookName string `gorm:"column:bookName"`
BookCounts int `gorm:"column:bookCounts"`
Detail string `gorm:"column:detail"`
}
func main() {
//1.定义连接信息,用户名、密码、通信协议等信息
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
//连接数据库,连接数据库时,可以加上一些高级配置,就是gorm.Config中的参数
db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
return
}
//2.查询
var book Books
//2.1 db.First() 按照主键升序排列,取第一条数据
//select * from books order by bookId limit 1
//创建一个books对象,让查出来的数据赋值到这个对象中
db.First(&book)
//2.2 db.Take() 获取一条数据,没有指定排序字段
//select * from books limit 1
//db.Take(&book)
//fmt.Println(book)
//2.3 db.Last() 按照主键降序排列,取第一条数据
//select * from books order by bookId desc limit 1
db.Last(&book)
fmt.Println(book)
}
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建books实体
type Books struct {
//注意:当实体和数据库名称不一致时,需要起别名来进行查询
BookID int `gorm:"column:bookID",gorm:"primary_key"`
BookName string `gorm:"column:bookName"`
BookCounts int `gorm:"column:bookCounts"`
Detail string `gorm:"column:detail"`
}
func main() {
//1.定义连接信息,用户名、密码、通信协议等信息
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
//连接数据库,连接数据库时,可以加上一些高级配置,就是gorm.Config中的参数
db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
return
}
//多记录查询,需要使用Books数组
books := []Books{}
db.Find(&books)
fmt.Println(books)
}
string条件
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建books实体
type Books struct {
//注意:当实体和数据库名称不一致时,需要起别名来进行查询
BookID int `gorm:"column:bookID",gorm:"primary_key"`
BookName string `gorm:"column:bookName"`
BookCounts int `gorm:"column:bookCounts"`
Detail string `gorm:"column:detail"`
}
func main() {
//1.定义连接信息,用户名、密码、通信协议等信息
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
//连接数据库,连接数据库时,可以加上一些高级配置,就是gorm.Config中的参数
db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
return
}
//4.使用条件进行索引
//4.1 string条件
//4.1.1 获取满足条件并且按主键升序排列的首条记录
//var book Books
//sql:select * from books where bookName = 'Linux' order by id limit 1
//db.Where("bookName=?", "Linux").First(&book)
//fmt.Println(book)
//4.1.2 获取满足条件的所有记录
//books := []Books{}
//sql:select * from books where bookCounts=10
//db.Where("bookCounts", 10).Find(&books)
//fmt.Println(books)
//4.1.3 除过满足条件的记录,查询出其他所有记录
//books := []Books{}
select * from books where bookName <> 'Linux'
//db.Where("bookName <> ?", "Linux").Find(&books)
//fmt.Println(books)
//4.1.4 模糊查询
//由于模糊查询可能是一条数据,也可能是多条数据,所以使用数组接收
//books := []Books{}
sql:select * from books bookName like %Li%
//db.Where("bookName like ?", "%Li%").Find(&books)
//fmt.Println(books)
//4.1.5 多条件查询
//var book Books
//db.Where("bookName = ? and bookCounts = ?", "mysql", 10).Find(&book)
//fmt.Println(book)
//4.1.6 使用between
books := []Books{}
db.Where("bookCounts between ? and ?", 1, 20).Find(&books)
fmt.Println(books)
}
Struct&Map条件
//其实使用Struct和Map就和mybatis中使用对象和map是一样的
//5.使用Struct和Map进行条件查询
//5.1 使用Struct查询
//var book Books
//db.Where(Books{BookName: "Linux"}).Find(&book)
//fmt.Println(book)
//5.2 使用Map查询
var book Books
maps := make(map[string]string)
maps["bookName"] = "Linux"
//直接将map放进就行
db.Where(maps).Find(&book)
fmt.Println(book)
选择特定字段查询
//6.选择特定字段查询
books := []Books{}
db.Select("bookID", "bookName").Where("bookCounts", 10).Find(&books)
fmt.Println(books)
limit & offset
//注意:
// gorm中没有limit 1,2,所以只能使用offset来进行偏移
// limit 1,2 --》 limit 2 offset 1
//7.limit & offset
//7.1 limit
//books := []Books{}
//sql:select * from books limit 3 即取第1条数据--第3条数据
//db.Limit(3).Find(&books)
//注意:在gorm中不能使用Limit 1,2 这样的用法,所以只能配合offset来使用
//fmt.Println(books)
//7.2 offset & limit
books := []Books{}
//sql:select * from books limit 2 offset 1 注意:不包括第1条数据
db.Limit(2).Offset(1).Find(&books)
fmt.Println(books)
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建books实体
type Books struct {
//注意:当实体和数据库名称不一致时,需要起别名来进行查询
BookID int `gorm:"column:bookID",gorm:"primary_key"`
BookName string `gorm:"column:bookName"`
BookCounts int `gorm:"column:bookCounts"`
Detail string `gorm:"column:detail"`
}
func main() {
//1.创建连接
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
//判空
if err != nil {
fmt.Println("连接失败")
return
}
//删除记录
//1.根据主键删除
//sql:delete from books where id =4
//db.Delete(Books{}, 4)
//2.根据条件删除
db.Where("bookName = ?", "Linux").Delete(Books{})
}
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//创建books实体
type Books struct {
//注意:当实体和数据库名称不一致时,需要起别名来进行查询
BookID int `gorm:"column:bookID",gorm:"primary_key"`
BookName string `gorm:"column:bookName"`
BookCounts int `gorm:"column:bookCounts"`
Detail string `gorm:"column:detail"`
}
func main() {
//1.创建连接
url := "root:drldrl521521@tcp(localhost:3306)/ssmbuild?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
//判空
if err != nil {
fmt.Println("连接失败")
return
}
//更新数据
//1.更新一列
//db.Model(Books{}).Where("bookName", "Java").Update("bookCounts", 15)
//2.更新多列
//2.1 使用struct更新
//db.Model(Books{}).Where("bookName", "Java").Updates(Books{BookCounts: 20, Detail: "Java狗都不学"})
//2.2 使用map更新
db.Model(Books{}).Where("bookName", "MySQL").Updates(map[string]interface{}{"BookCounts": "33", "Detail": "MySQL太难了"})
}