go连接数据库(简单的查询学习)
一、go自带
1.下载依赖
go get -u github.com/go-sql-driver/mysql
2.插入数据
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
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
}
stm, err := db.Prepare("insert into books values(default ,?,?,?)")
defer func() {
if stm != nil {
stm.Close()
}
}()
if err != nil {
fmt.Println("预处理失败")
return
}
res, err := stm.Exec("go", 1, "go语言从入门到入坟")
if err != nil {
fmt.Println("sql执行失败")
return
}
count, err := res.RowsAffected()
if err != nil {
fmt.Println("结果获取失败")
return
}
if count > 0 {
fmt.Println("新增成功")
} else {
fmt.Println("新增失败")
}
id, err := res.LastInsertId()
fmt.Println(id)
}
2.1 获取插入数据主键id
id, err := res.LastInsertId()
fmt.Println(id)
3.更新数据
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
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
}
stm, err := db.Prepare("update books set bookCounts = ?")
defer func() {
if stm != nil {
stm.Close()
}
}()
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("更新成功")
}
}
4.删除数据
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
if err != nil {
fmt.Println("连接失败")
return
}
defer func() {
db.Close()
}()
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("删除成功")
}
}
5.查询数据
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:drldrl521521@tcp(localhost:3306)/ssmbuild")
if err != nil {
fmt.Println("连接失败")
return
}
defer func() {
db.Close()
}()
db.Ping()
stm, err := db.Prepare("select * from books")
if err != nil {
fmt.Println("预处理失败")
return
}
defer func() {
stm.Close()
}()
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)
}
}
二、GORM
1.下载依赖
go get -u github.com/jinzhu/gorm
2.连接数据库(mysql)
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"
_, err := gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
return
} else {
fmt.Println("连接成功")
}
}
3.根据go创建表
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
UserId int `gorm:"primary_key"`
UserName string
UserSex string
}
func main() {
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
}
db.AutoMigrate(&User{})
}
4.插入数据
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
UserId int `gorm:"primary_key"`
UserName string
UserSex string
}
func main() {
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
}
user := User{1, "张三", "男"}
db.Create(user)
}
5.查询数据
5.1 First&Take&Last
#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"
)
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() {
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
}
var book Books
db.First(&book)
db.Last(&book)
fmt.Println(book)
}
5.2 多记录查询
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
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() {
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
}
books := []Books{}
db.Find(&books)
fmt.Println(books)
}
5.3 条件查询
string条件
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
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() {
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
}
books := []Books{}
db.Where("bookCounts between ? and ?", 1, 20).Find(&books)
fmt.Println(books)
}
Struct&Map条件
var book Books
maps := make(map[string]string)
maps["bookName"] = "Linux"
db.Where(maps).Find(&book)
fmt.Println(book)
选择特定字段查询
books := []Books{}
db.Select("bookID", "bookName").Where("bookCounts", 10).Find(&books)
fmt.Println(books)
limit & offset
books := []Books{}
db.Limit(2).Offset(1).Find(&books)
fmt.Println(books)
6.删除数据
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
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() {
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
}
db.Where("bookName = ?", "Linux").Delete(Books{})
}
7.更新数据
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
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() {
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
}
db.Model(Books{}).Where("bookName", "MySQL").Updates(map[string]interface{}{"BookCounts": "33", "Detail": "MySQL太难了"})
}
|