How can I compile the Go database / sql program with multiple drivers?

I am writing a test program in Go for sql databases (Postgres and Mysql) currently. I don’t know much about the “_” option for packages, but I use it (see below).

What I would like to do is collect once to use several SQL drivers for one RDBMS, as well as for several RDBMS and when starting the program, select which driver and RDBMS to use. I am not sure if this is possible. I am currently compiling with one Postgres and one Mysql driver, and then choosing which one I use at runtime (Postgres / Mysql). This works fine, but I need to remember which driver was compiled. It would be nice to compile several drivers for one RDBMS, and then at runtime choose which one to use. I think this is impossible. Alternatively, it would be nice to be able to choose at compile time which drivers to use, and at run time to know which drivers are used. Without one of these means, for example,conduct testing. Postgres and I think that they use one driver when in fact the program was compiled with another driver.

Is it possible to have a compiler option to select specific drivers, and then at runtime know which driver is used? Alternatively, obviously, for editing a program to indicate this.

An import example is as follows:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    ////_ "github.com/lib/pq"
    _ "github.com/lxn/go-pgsql"
 ........
+4
source share
1 answer

I know little about the “_” option for packages, but I use it (see below).

Turning _into an import path will import the package as usual (with its function init()), but it will not associate the name in your current package with the imported package.

, , - , SQL- RDBMS, RDBMS , RDBMS . , .

init() "github.com/go-sql-driver/mysql" :

func init() {
        sql.Register("mysql", &MySQLDriver{})
}

database/sql Register , :

func Register(name string, driver driver.Driver)

:

, .

sql.Open:

func Open(driverName, dataSourceName string) (*DB, error)

, , , :

db, e := sql.Open("mysql", "user:pass@host:port")

, github.com/lxn/go-pgsql init() :

func init() {
        sql.Register("postgres", sqlDriver{})
}

, , , .

flag :

./my_app -driver=mysql -db="user:pass@host:port"

sql.Open.

+5

All Articles