go语言 func (mysql_go语言:数据库操作之MySql

package main

import (

"database/sql"

_ "github.com/Go-SQL-Driver/MySQL"

"log"

)

func initMysql() *sql.DB {

//打开数据库连接Open(驱动名,连接字符串)

db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")

if err != nil {

log.Fatal(err)

}

return db

}

func query() {

db := initMysql()

defer db.Close()

row, err := db.Query("select * from user")

if err != nil {

log.Fatal(err)

}

var name string = ""

var id int = 0

var password string = ""

for row.Next() {

row.Scan(&name, &id, &password)

log.Println("id:", id, ",name:", name, "password:", password)

}

}

func insert() {

db := initMysql()

defer db.Close()

result, _ := db.Exec("insert into user values(?,?,?)", "test", 2, "test")

c, _ := result.RowsAffected()

log.Println("add affected rows:", c)

}

func delete() {

db := initMysql()

defer db.Close()

result, _ := db.Exec("delete from user where id = ?", 2)

c, _ := result.RowsAffected()

log.Println("delete affected rows:", c)

}

func update() {

db := initMysql()

defer db.Close()

result, _ := db.Exec("update user set password = ? where id = ?", "kk", 1)

c, _ := result.RowsAffected()

log.Println("update affected rows:", c)

}

func main() {

insert()

query()

delete()

update()

}

有疑问加站长微信联系(非本文作者)

5c5fbae790ec0313d6ee17e8b3dd9ba1.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值