Go语言之mysql

1.导入Go-MySQL-Driver驱动包

在命令行输入

go get github.com/go-sql-driver/mysql

2.go语言连接并操作MySQL数据库

代码如下

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main(){
	db,err:=sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/testgo?charset=utf8")
	if err!=nil{
		panic(err)
	}else{
		fmt.Println(db.Stats())
	}

	//插入用户

	//statement,err:=db.Prepare("insert into user set username=?,password=?")
	statement,err:=db.Prepare("insert into user(username,password) values(?,?)")

	if err!=nil{
		panic(err)
	}else{
		//fmt.Println(statement)
		res,err:=statement.Exec("wangwu","wangwu1111")

		if err!=nil{
			panic(err)
		}else{
			//打印最后插入的id

			fmt.Println(res.LastInsertId())
		}
	}
	//修改用户

	statement1,err:=db.Prepare("update user set username=? where id=?")
	if err!=nil{
		panic(err)
	}else{
		res,err:=statement1.Exec("wangwu1",3)
		if err!=nil{
			panic(err)
		}else{
			//打印影响的行
			fmt.Println(res.RowsAffected())
		}
	}
	//删除用户
	statement2,err:=db.Prepare("delete  from user where id=?")
	if err!=nil{
		panic(err)
	}else{
		res,err:=statement2.Exec(1)
		if err!=nil{
			panic(err)
		}else{
			//打印影响的行
			fmt.Println(res.RowsAffected())
		}
	}
	//rows,err:=db.Query("select  * from user where id=2")

	rows,err:=db.Query("select  * from user where username='"+"Sarah"+"'")


	for rows.Next(){
		var id int
		var username string
		var password string
		//获取一行的数据
		err=rows.Scan(&id,&username,&password)

		if err!=nil{
			panic(err)
		}else{
			fmt.Println("id:",id," username:",username," password:",password)
		}
	}

	db.Close()


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值