Introducing the SQLX package

Import ("fmt"
  	"github.com/jmoiron/sqlx"Copy the code

Define the database parameter configuration

var (
	sqlxdbConfig = DBConfig{
		Host:     "127.0.0.1", // ip
		Port:     5432,   // psql  5432
		UserName: "zyf"// user name Password:"123"// password DBName:"sqlxdb", // database} SQLXDB * sqlx.db) // Database configurationtype DBConfig struct {
	Host     string
	Port     int32
	UserName string
	Password string
	DBName   string
}
Copy the code

Function to deal with

type Req struct{
	id   int   `json:"id" db:"id"} // main function funcmainSqlxReq := make([]Req, 0) SQL :="select * from sqlx"
	iferr := sqlxdb.Unsafe().Select(&sqlxReq, sql2); err ! = nil { fmt.Printf(" err:%v\n", err)
		returnFunc (c DBConfig) ToString() string {return fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable", c. host, c. port, C. ussername, c. password, c. dbname,)} func postgres(dbconfig dbconfig) * sqlx.db { err := sqlx.Open("postgres", dbconfig.ToString())
	iferr ! Db.setmaxidleconns (10) = nil {fmt.printf (err)} // Maximum link count db.setMaxIdleconns (10)return db
}
Copy the code

For details about the use of SQL statements, see the official documentation: go-database-sql.org/index.html