如何在GoLang上的不同处理程序上全局共享MySQL驱动程序

huangapple go评论92阅读模式
英文:

How to share globally the MySQL driver on different handlers on GoLang

问题

我想从不同的处理程序中调用数据库,这是我的mysql.go代码:

package common

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB
var err error

// 连接数据库
func connectDB() {
	db, err = sql.Open("mysql", "root@tcp(localhost:3306)/mysqlapi")
	if err != nil {
		fmt.Println(err.Error())
	}
	defer db.Close()

	// 测试连接
	err = db.Ping()
	if err != nil {
		fmt.Println(err.Error())
	}

	// 表迁移
	stmt, err := db.Prepare("CREATE TABLE person (id int NOT NULL AUTO_INCREMENT, first_name varchar(40), last_name varchar(40), PRIMARY KEY (id));")
	if err != nil {
		fmt.Println(err.Error())
	}
	_, err = stmt.Exec()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println("Person Table successfully migrated....")
	}
}

这是我想要做的,但我不知道如何从common包中调用不同包中的db(我尝试了common.db,但它不起作用):

package models

import (
	"github.com/colombia9503/RESTful-Mysql/common"
)

type User struct {
	Id         int
	First_Name string
	Last_Name  string
}

var Users = new(users)

type users struct{}

func (users) SelectAll() ([]*User, error) {
	var users []*User
	rows, err := common.db.Query("select id, first_name, last_name from person;")
	if err != nil {
		panic(err)
	}

	for rows.Next() {
		// 一些代码...
	}
	return users, err
}

func (users) SelectOne(id string) (*User, error) {
	// 一些代码...
}

func (users) Insert(name, last_name string) (*User, error) {
	// 一些代码...
}

func (users) Update(id, name, last_name string) error {
	// 一些代码...
}

func (users) Delete(id string) error {
	// 一些代码...
}

你可以尝试将common.db更改为common.DB,因为在common包中,db是一个全局变量,需要以大写字母开头才能在其他包中访问。

英文:

I want to call db from the different handlers, This is my mysql.go:
<!-- language: golang -->
package common

import (
	&quot;database/sql&quot;
	&quot;fmt&quot;

	_ &quot;github.com/go-sql-driver/mysql&quot;
)

var db *sql.DB
var err error

//db connection
func connectDB() {
	db, err = sql.Open(&quot;mysql&quot;, &quot;root@tcp(localhost:3306)/mysqlapi&quot;)
	if err != nil {
		fmt.Println(err.Error())
	}
	defer db.Close()

	//test connection
	err = db.Ping()
	if err != nil {
		fmt.Println(err.Error())
	}

	//table migration
	stmt, err := db.Prepare(&quot;CREATE TABLE person (id int NOT NULL AUTO_INCREMENT, first_name varchar(40), last_name varchar(40), PRIMARY KEY (id));&quot;)
	if err != nil {
		fmt.Println(err.Error())
	}
	_, err = stmt.Exec()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(&quot;Person Table successfully migrated....&quot;)
	}

}

this is what i want to do, but i don't know how i call db from common package into a different package (i tried common.db but it doesn't works):

<!-- language: golang -->

package models

import (
	&quot;github.com/colombia9503/RESTful-Mysql/common&quot;
)

type User struct {
	Id         int
	First_Name string
	Last_Name  string
}

var Users = new(users)

type users struct{}

func (users) SelectAll() ([]*User, error) {
	var users []*User
	rows, err := common.db.Query(&quot;select id, first_name, last_name from person;&quot;)
	if err != nil {
		panic(err)
	}

	for rows.Next() {
        some code..
	}
	return users, err
}

func (users) SelectOne(id string) (*User, error) {
	some code..
}

func (users) Insert(name, last_name string) (*User, error) {
	some code..
}

func (users) Update(id, name, last_name string) error {
	some code..
}

func (users) Delete(id string) error {
	some code..
}

答案1

得分: 0

你需要像这样编写你的 db 变量:

package common

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

var Db *sql.DB
var Err error

在 Golang 中,大写字母表示将其导出到包外部。你可以在这里了解更多信息:这里

英文:

You need to write your db var like this :

package common

import (
    &quot;database/sql&quot;
    &quot;fmt&quot;

    _ &quot;github.com/go-sql-driver/mysql&quot;
)

var Db *sql.DB
var Err error

In Golang Capital letter means exporting it to outside of the package.you can learn more about this here

huangapple
  • 本文由 发表于 2017年1月11日 06:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41579222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定