当前位置:网站首页>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("删除成功")
}
边栏推荐
- 对于升级go1.18的goland问题
- 阿里三面:MQ 消息丢失、重复、积压问题,该如何解决?
- 金山打字通 官网 下载
- weight distribution
- 小白的0基础教程SQL: 安装MYSQL 03
- Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
- MVVM项目开发(商品管理系统一)
- MATLAB program design and application of MATLAB 2.5
- Offer brush questions - 1
- Golang:go开启web服务
猜你喜欢
AspNet.WebApi.Owin custom Token request parameters
【视觉SLAM十四讲】第一章理论详解
升级为重量级锁,锁重入会导致锁释放?
Srping中bean的生命周期
leetcode125 Verify palindrome string
matlab simulink 粒子群优化模糊pid控制的电机泵
Dbeaver connect the MySQL database and error Connection refusedconnect processing
Motion analysis and parameter optimization of crank-slider mechanism
Json对象和Json字符串的区别
Vim简介
随机推荐
JS的运行原理
从零开始—仿牛客网讨论社区项目(一)
表的创建、修改与删除
Golang:go获取url和表单属性值
2022.7.26 Mock Competition
阿里三面:MQ 消息丢失、重复、积压问题,该如何解决?
MVVM project development (commodity management system 1)
升级为重量级锁,锁重入会导致锁释放?
响应式织梦模板园林花卉类网站
crypto-js uses
信息系统项目管理师必背核心考点(五十六)配置控制委员会(CCB)的工作
Dart exception details
NUMPY
The Bean's life cycle
uva12326
LeetCode 0149. 直线上最多的点数
Leetcode第 304 场周赛
Introduction to the basic principles, implementation and problem solving of crawler
曲柄滑块机构运动分析和参数优化
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