当前位置:网站首页>Golang: go to connect and use mysql
Golang: go to connect and use mysql
2022-08-01 07:02:00 【ZzzWClock】
go连接和使用mysql
一.依赖下载
// 终端下载mysql驱动
go get github.com/go-sql-driver/mysql
二.连接mysql
// 使用到database/sql包
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func mian() {
// 有两个参数 第一个是driver驱动 第二个是 mysql的连接参数
// 用户名:密码@tcp(ip地址:端口号)/数据库名称 The password can be left blank
db, err := sql.Open("mysql", "dbname:[email protected](ipaddress:port)/databsename")
if err != nil {
panic(err.Error())
}
fmt.Println(db)
}
三.创建mysql表
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func mian() {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/ceshi")
if err != nil {
panic(err.Error())
}
// sql语句
sql := ` CREATE TABLE test( id int(11) NOT NULL AUTO_INCREMENT, name varchar(64) NOT NULL COMMENT '姓名', password varchar(32) NOT NULL COMMENT '密码', email varchar(32) NOT NULL COMMENT '电子邮箱', PRIMARY KEY (id) ) ENGINE=InnoDB CHARSET=utf8 COMMENT='测试表'; `
// 执行这条sql语句
_, err = db.Exec(strings.Trim(sql, " "))
if err != nil {
panic(err.Error())
}
}
四.使用mysql事物
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func mian() {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/ceshi")
if err != nil {
panic(err.Error())
}
// 开始事物 returns a transaction pointer
begin, err := db.Begin()
if err != nil {
panic(err.Error())
}
// sql语句
sql := "INSERT INTO test (`name`, `password`, `email`) VALUES(?,?,?)"
// 使用msyqlThe preprocessing mechanism preventssql注入 返回一个stmt指针
stmt, err := begin.Prepare(sql)
if err != nil {
// 事物回滚
begin.Rollbak()
panic(err.Error())
}
// 执行这条sqlstatement and give placeholders`?`填充参数
_, err = stmt.Exec("王武", "a123456", "[email protected]")
if err != nil {
// 事物回滚
begin.Rollbak()
panic(err.Error())
}
// 事物提交
begin.Commit()
}
五.查询数据
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/ceshi")
if err != nil {
panic(err.Error())
}
// 开始事物 returns a transaction pointer
begin, err := db.Begin()
if err != nil {
panic(err.Error())
}
// sql 语句 查询一条数据
sql := "select id, name, password, email from test where id = ? for update"
row := t.QueryRow(sql, 2)
var id int
var name string
var password string
var email string
err = row.Scan(&id, &name, &password, &email)
if err != nil {
t.Rollback()
panic(err.Error())
}
t.Commit()
fmt.Println(id, name, password, email)
// 查询多条数据
sql := "select id, name, password, email from test"
rows, err := t.Query(sql)
if err != nil {
t.Rollback()
panic(err.Error())
}
users := make([]map[string]interface{
}, 0)
for rows.Next() {
maps := make(map[string]interface{
}, 4)
var id int
var name string
var password string
var email string
err = rows.Scan(&id, &name, &password, &email)
maps["id"] = id
maps["name"] = name
maps["password"] = password
maps["email"] = email
if err != nil {
t.Rollback()
panic(err.Error())
}
users = append(users, maps)
}
t.Commit()
for _, v := range users {
fmt.Printf("id: %d, name: %s, password: %s, email: %s \n", v["id"], v["name"], v["password"], v["email"])
}
}
六.删除数据
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/ceshi")
if err != nil {
panic(err.Error())
}
// 开始事物 returns a transaction pointer
begin, err := db.Begin()
if err != nil {
panic(err.Error())
}
// sql 语句 删除数据
sql := "delete from test where id = ?"
_, err = t.Exec(sql, 1)
if err != nil {
t.Rollback()
panic(err.Error())
}
t.Commit()
fmt.Println("删除成功")
}
边栏推荐
猜你喜欢
随机推荐
Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
日志导致线程Block的这些坑,你不得不防
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
matlab simulink 粒子群优化模糊pid控制的电机泵
weight distribution
05-SDRAM: Arbitration
Golang:go连接和使用mysql
Introduction to the basic principles, implementation and problem solving of crawler
Dialogue with the father of MySQL: One excellent programmer is worth 5 ordinary programmers
NIO programming
Create, modify and delete tables
太厉害了,终于有人能把文件上传漏洞讲的明明白白了
Why is the lightweight VsCode used more and more?Why eat my C drive 10G?How to Painlessly Clean VsCode Cache?Teach you how to lose weight for C drive
拳头游戏免版权音乐下载,英雄联盟无版权音乐,可用于视频创作、直播
Dart 异常详解
解决浏览器滚动条导致的页面闪烁问题
dbeaver连接MySQL数据库及错误Connection refusedconnect处理
【FiddlerScript】利用FiddlerScript抓包保利威下载
小程序通过云函数操作数据库【使用get取数据库】
mysql中添加字段的相关问题








