golang中连接mysql数据库,操作数据库

Posted Leo Han

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang中连接mysql数据库,操作数据库相关的知识,希望对你有一定的参考价值。

golang中连接数据库需要首先下载对应数据库的客户端驱动,我们以mysql为例:

  1. 首先下载mysql客户端驱动:
go get github.com/go-sql-driver/mysql

然后通过sql.Open获取一个数据库连接:

url :="root:123456@tcp(127.0.01)/golang"
con,err := sql.Open("mysql",url)

接下来我们看看怎么操作数据库:

package model

import (
	"database/sql"
	"fmt"
)

type ExecutorGroup struct 
	Model
	Name string `json:"name" db:"name"`
	Description string `json:"description" db:"description"`
	Urls string `json:"urls" db:"urls"`




func GetAllExecutorGroup(con *sql.DB)([]ExecutorGroup,error) 
	querySql := "select id,name,description,urls from executor_group"
	rows,err := con.Query(querySql)
	if err != nil 
		return nil,err
	
	result := make([]ExecutorGroup,0)
	index := 0
	for rows.Next() 
		var row ExecutorGroup
		rows.Scan(&row.Id,&row.Name,&row.Description,&row.Urls)
		result = append(result,row)
		index ++
	
	fmt.Println(index)
	return result,err


func GetExecutorGroupById(con *sql.DB,id uint)(*ExecutorGroup,error) 
	querySql :=  fmt.Sprintf("select id,name,description,urls from executor_group where id = %d ",id)
	rows,err := con.Query(querySql)
	if err != nil 
		return nil,err
	
	if rows.Next() 
		var group ExecutorGroup
		rows.Scan(&group.Id,&group.Name,&group.Description,&group.Urls)
		return &group,nil
	
	return nil,nil

func InsertExecutorGroup(con *sql.DB,executorGroup *ExecutorGroup) error 
	tx,err := con.Begin()
	if err != nil 
		return err
	
	insertSql := "insert into executor_group(name,description,urls) values(?,?,?)"
	stmt ,err := tx.Prepare(insertSql)
	if err != nil 
		return err;
	

	_ ,err = stmt.Exec(executorGroup.Name,executorGroup.Description,executorGroup.Urls)

	tx.Commit()

	return err;


func UpdateExecutorGroup(con *sql.DB ,executorGroup *ExecutorGroup) error 
	tx,err := con.Begin()
	if err != nil 
		return err
	
	insertSql := "update executor_group set name=?,description=?,urls=? where id =? "
	stmt ,err := tx.Prepare(insertSql)
	if err != nil 
		return err;
	
	_ ,err = stmt.Exec(executorGroup.Name,executorGroup.Description,executorGroup.Urls)
	return err;


func DeleteExecutorGroup(con *sql.DB ,id int) error 
	tx,err := con.Begin()
	if err != nil 
		return err
	
	deleteSql := fmt.Sprintf("delete from executor_group where id =%d ",id)
	_,err = tx.Exec(deleteSql)
	if err != nil 
		return err;
	
	err = tx.Commit()
	return err;





如上,对应常见的数据库的增删改查,并加上事务

以上是关于golang中连接mysql数据库,操作数据库的主要内容,如果未能解决你的问题,请参考以下文章

golang 连接、操作完mysql, 对mysql的连接会自动关闭,还是必须要手动关闭?

GoLang如何操作mysql

Golang中mysql数据库的使用

golang学习----数据库操作

golang 碎片整理之MySQL

golang操作数据库