Preface
MySQL is the most common relational database in development and the database that programmers deal with the most. Using Go to manipulate the database requires Go to use its owndatabase/sql
and drivego-sql-driver/mysql
To achieve it. This article mainly summarizes how to use Go language to operate the MySql database. Friends who need it can refer to the following content, hoping it will be helpful to everyone.
Download dependencies
database/sql
It is one of the standard libraries for Go to operate databases. It provides a series of interface methods for accessing databases (mysql, sqllite, oralce), but it does not provide database-specific methods, and those unique methods need to be handed over to the database driver for processing.
In our usual work, we use more of the jmoiron/sqlx package to operate the database. SQLx is an extension based on the standard library, and we can operate various types of data through SQLx.
go get -u /go-sql-driver/mysql go get -u /jmoiron/sqlx
Using MySQL Driver
Open
Open adirverName
The specified database,dataSourceName
Specifying a data source generally includes at least the database file name and other information necessary for connection.
func Open(driverName, dataSourceName string) (*DB, error)
It returns aDatabase type, it is not a database connection. The connection in Go comes from the internally implemented connection pool. The establishment of the connection is lazy. The connection will be created and maintained by the connection pool during operation. It can be safely used by multiple goroutines at the same time.
Example:
package main import ( "database/sql" _ "/go-sql-driver/mysql" ) var db * //Declare a global db variable func main() { // Initialize MySQL err := initDB() if err != nil { panic(err) } defer () // Note that this line of code should be written below the err judgment above} //initDB initializes MySQLfunc initDB() (err error) { // It will not verify whether the account password is correct db, err = ("mysql", "root:123456@tcp(127.0.0.1:3306)/test") if err != nil { return err } // Try to establish a connection with the database (check that dsn is correct) err = () if err != nil { return err } return nil }
Notice:
-
It will only verify that the format is correct and the database will not be connected.
-
It will connect to the database to determine whether the user, password, IP address, and port are correct.
-
exist
err
Then, because the opening may not be successful, close a connection that is not open.
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 that matches the maximum number of open connections. If n<=0, the maximum number of open connections will not be limited, and the default is 0 (unlimited).
SetMaxIdleConns
func (db *DB) SetMaxIdleConns(n int)
SetMaxIdleConns
Sets the maximum number of idle connections in the connection pool. If n is greater than the maximum number of open connections, the new maximum number of idle connections will be reduced to the limit that matches the maximum number of open connections. If n<=0, idle connections are not retained.
operate
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) func (db *DB) QueryRow(query string, args ...interface{}) *Row func (db *DB) Exec(query string, args ...interface{}) (Result, error) func (db *DB) Prepare(query string) (*Stmt, error)
()
: Return multiple rows of data, it needs to traverse in sequence, and you need to close the query result set yourself.
()
:Specially query a row of data syntax, returnErrNoRow
Or a row of data, you don't need to close the result set yourself.
()
: Used to executeinsert
、update
、delete
Wait for operations that do not need to return the result set.
()
: Pre-connect a database(con)
And a stripsql
Statement binding and returnstmt
The structure represents the bound connection and then run()
or()
;stmt
It is concurrently safe. This is because every direct call will automatically select an available one.con
, each time you choose not the samecon
。
This is the article about the basic knowledge summary of Go language implementation MySQL. For more information about Go language operation MySQL, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!