go测试mysql

2019-12-8 流沙 Golang

CRUD的一个简单的DMEO

package ch1

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

func sqlInsert(db *sql.DB) int64{
	stmt,err := db.Prepare("insert into test1 (age,name) VALUES (?,?)")
	res,err:= stmt.Exec(12,"hao123")
	if err!=nil{
		panic(err)
	}
	id,err:=res.LastInsertId()
	return id
}

func sqlDelete(db *sql.DB,id int) int64 {
	stmt,err := db.Prepare("delete from test1 where id=?")
	res,err:= stmt.Exec(id)
	if err!=nil{
		panic(err)
	}
	rows,err:=res.RowsAffected()
	return rows
}

func sqlUpdate(db *sql.DB,name string,age int,id int) int64 {
	stmt,err := db.Prepare("update test1 set name=?,age=? where id=? ")
	res,err:= stmt.Exec(name,age,id)
	if err!=nil{
		panic(err)
	}
	rows,err:=res.RowsAffected()
	return rows
}

//查询一条
func sqlSelectOne(db *sql.DB,id int) {
	rows, err := db.Query("select * from test1 where id="+strconv.Itoa(id)+" limit 1")
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	for rows.Next() {
		//定义变量接收查询数据
		var id,age int
		var name string

		err := rows.Scan(&id,&age,&name)
		if err != nil {
			panic(err)
		}
		fmt.Println(id,age,name)
	}
	//关闭结果集(释放连接)
	rows.Close()
	}

//查询多条
func sqlSelectRows(db *sql.DB)  {
	rows, err := db.Query("select * from test1")
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	for rows.Next() {
		//定义变量接收查询数据
		var id,age int
		var name string

		err := rows.Scan(&id,&age,&name)
		if err != nil {
			panic(err)
		}
		fmt.Println(id,age,name)
	}
	//关闭结果集(释放连接)
	rows.Close()

}


func TestSql(t *testing.T)  {

	//t.Log("Hello World!")

	db,err:=sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/thinkphp2?charset=utf8")
	if err!=nil{
		panic(err)
	}
	//数据增加
	/*
	id:=sqlInsert(db)
	t.Log("insert id=",id)
	*/
	//数据删除
	/*
	rows:=sqlDelete(db,11)
	t.Log("delete rows=",rows)
	*/

	//数据修改
	/*
	rows:=sqlUpdate(db,"gyarmy",7,10)
	t.Log("update rows=",rows)
	*/

	//数据查询
	//sqlSelectOne(db,10)
	sqlSelectRows(db)

	db.Close()

}

发表评论:

Powered by 流沙团

备案号:鄂ICP备15017378号-1