How to use CURD to operate MySQL in Go language
How to use CURD to operate MySQL in Go language. In view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
To create a Go project, you need to reference-driven dependencies:
Go get-u github.com/go-sql-driver/mysql
Use the MySQL driver:
Func Open (driverName, dataSourceName string) (* DB, error)
Open opens a database specified by dirverName, and dataSourceName specifies the data source, generally including at least the database file name and other necessary information for the connection.
Initialize the connection
Var db * sql.DB / / declare a global db variable / / initialize the MySQL function func initMySQL () (err error) {dsn: = "root:password@tcp (127.0.0.1 db 3306) / dbname" db, err = sql.Open ("mysql") Dsn) if err! = nil {return} err = db.Ping () if err! = nil {return} return} func main () {/ / initialize MySQL err: = initMySQL () if err! = nil {panic (err)} defer db.Close ()}
After initializing the connection to MySQL, you need to use the db.Ping function to determine whether the connection is successful or not.
SetMaxOpenConns
Func (db * DB) SetMaxOpenConns (n int)
SetMaxOpenConns sets the maximum number of connections to the database.
If n is greater than 0 and less than the maximum number of idle connections, the maximum number of idle connections will be reduced to the limit of matching the maximum number of open connections.
If n