当前位置:网站首页>Golang:go连接和使用mysql
Golang:go连接和使用mysql
2022-08-01 06:50: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地址:端口号)/数据库名称 密码为空也可以不填
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())
}
// 开始事物 返回一个事物指针
begin, err := db.Begin()
if err != nil {
panic(err.Error())
}
// sql语句
sql := "INSERT INTO test (`name`, `password`, `email`) VALUES(?,?,?)"
// 使用msyql的预处理机制防止sql注入 返回一个stmt指针
stmt, err := begin.Prepare(sql)
if err != nil {
// 事物回滚
begin.Rollbak()
panic(err.Error())
}
// 执行这条sql语句并且给占位符`?`填充参数
_, 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())
}
// 开始事物 返回一个事物指针
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())
}
// 开始事物 返回一个事物指针
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("删除成功")
}
边栏推荐
猜你喜欢

声音信号处理基频检测和时频分析

MATLAB程序设计与应用 2.5 MATLAB运算

Dell PowerEdge Server R450 RAID Configuration Steps

Srping bean in the life cycle

湖仓一体电商项目(一):项目背景和架构介绍

MVVM project development (commodity management system 1)

Win任务栏图标异常解决

企业员工人事管理系统(数据库课设)
![Explosive 30,000 words, the hardest core丨Mysql knowledge system, complete collection of commands [recommended collection]](/img/7f/08b323ffc5b5f8e3354bee6775b994.png)
Explosive 30,000 words, the hardest core丨Mysql knowledge system, complete collection of commands [recommended collection]

从购买服务器到网站搭建成功保姆级教程~超详细
随机推荐
Solve the problem of page flicker caused by browser scroll bars
curl (7) Failed connect to localhost8080; Connection refused
仿牛客网讨论社区项目—项目总结及项目常见面试题
NUMPY
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
数据湖:数据同步工具NiFi
crypto-js使用
响应式织梦模板园林花卉类网站
MySQL row locks and gap locks
响应式织梦模板园林景观类网站
Hunan institute of technology in 2022 ACM training sixth week antithesis
牛客刷SQL---2
sum of special numbers
[Translation] Securing cloud-native communications: From ingress to service mesh and beyond
The BP neural network based on MATLAB voice characteristic signal classification
Offer brush questions - 1
rhcsa 第三次
Flip letters using string container
Create, modify and delete tables
LeetCode 0150. Reverse Polish Expression Evaluation