当前位置:网站首页>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("删除成功")
}
边栏推荐
- NIO编程
- return;代表含义
- 牛客刷SQL---2
- Xiaobai's 0 Basic Tutorial SQL: An Overview of Relational Databases 02
- 点餐系统数据库设计--SQL Server
- Solve the problem of page flicker caused by browser scroll bars
- The BP neural network based on MATLAB voice characteristic signal classification
- 【一句话攻略】彻底理解JS中的回调(Callback)函数
- 插入排序—直接插入排序和希尔排序
- crypto-js uses
猜你喜欢
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
仿牛客网项目总结
NIO programming
Offer刷题——1
Data organization -- singly linked list of the linear table
目标检测概述-上篇
matlab 风速模型 小波滤波
Induction jian hai JustFE 2022/07/29 team, I learned the efficient development summary (years)
Introduction to the basic principles, implementation and problem solving of crawler
随机推荐
torch
NIO programming
小白的0基础教程SQL: 关系数据库概述 02
MVVM项目开发(商品管理系统一)
first unique character in characters
Data organization -- singly linked list of the linear table
第02章 MySQL的数据目录【1.MySQL架构篇】【MySQL高级】
2022年牛客多校第四场补题
Bean的生命周期
Create, modify and delete tables
基于MATLAB的BP神经网络进行语音特征信号分类
「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
日志导致线程Block的这些坑,你不得不防
零代码网站开发利器:WordPress
2022.7.27 Selected lectures on good topics
我说过无数遍了:从来没有一种技术是为灵活组合这个目标而设计的
「游戏引擎 浅入浅出」4.1 Unity Shader和OpenGL Shader
matlab simulink 粒子群优化模糊pid控制的电机泵
matlab wind speed model wavelet filtering
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.