Go-MySQL-Driver
A MySQL-Driver for Go's database/sql package

Features
- Lightweight and fast
- Native Go implementation. No C-bindings, just pure Go
- Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or custom protocols
- Automatic handling of broken connections
- Automatic Connection Pooling (by database/sql package)
- Supports queries larger than 16MB
- Full
sql.RawBytes support.
- Intelligent
LONG DATA handling in prepared statements
- Secure
LOAD DATA LOCAL INFILE support with file allowlisting and io.Reader support
- Optional
time.Time parsing
- Optional placeholder interpolation
- Supports zlib compression and optional zstd compression.
Requirements
- Go 1.25 or higher. We aim to support the 3 latest versions of Go.
- MySQL (8.0+) and MariaDB (10.11+) are supported by maintainers.
- TiDB is supported by PingCAP.
- Do not ask questions about TiDB in our issue tracker or forum.
- Document
- Forum
- go-mysql would work with Percona Server, Google CloudSQL or Sphinx (2.2.3+).
- Maintainers won't support them. Do not expect issues are investigated and resolved by maintainers.
- Investigate issues yourself and please send a pull request to fix it.
Installation
Simple install the package to your $GOPATH with the go tool from shell:
go get -u github.com/go-sql-driver/mysql
Make sure Git is installed on your machine and in your system's PATH.
Usage
Go MySQL Driver is an implementation of Go's database/sql/driver interface. You only need to import the driver and can use the full database/sql API then.
Use mysql as driverName and a valid DSN as dataSourceName:
import (
"database/sql"
"time"
_ "github.com/go-sql-driver/mysql"
)
// ...
db, err := sql.Open("mysql", "user:password@/dbname")
if err != nil {
panic(err)
}
// See "Important settings" section.
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
Examples are available in our Wiki.
Important settings
db.SetConnMaxLifetime() is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too.
db.SetMaxOpenConns() is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server.
db.SetMaxIdleConns() is recommended to be set same to db.SetMaxOpenConns(). When it is smaller than SetMaxOpenConns(), connections can be opened and closed much more frequently than you expect. Idle connections can be closed by the db.SetConnMaxLifetime(). If you want to close idle connections more rapidly, you can use db.SetConnMaxIdleTime() since Go 1.15.
DSN (Data Source Name)
The Data Source Name has a common format, like e.g. PEAR DB uses it, but without type-prefix (optional parts marked by squared brackets):
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
A DSN in its fullest form:
username:password@protocol(address)/dbname?param=value
Except for the databasename, all values are optional. So the minimal DSN is:
/dbname
If you do not want to preselect a database, leave dbname empty:
/
This has the same effect as an empty DSN string:
dbname is escaped by PathEscape() since v1.8.0. If your database name is dbname/withslash, it becomes:
/dbname%2Fwithslash
Alternatively, Config.FormatDSN can be used to create a DSN string by filling a struct.
Password
Passwords can consist of any character. Escaping is not necessary.
Protocol
See net.Dial for more information which networks are available.
In general you should use a Unix domain socket if available and TCP otherwise for best performance.
Address
For TCP and UDP networks, addresses have the form host[:port].
If port is omitted, the default port will be used.
If host is a literal IPv6 address, it must be enclosed in square brackets.
The functions net.JoinHostPort and net.SplitHostPort manipulate addresses in this form.
For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. /var/run/mysqld/mysqld.sock or /tmp/mysql.sock.
Parameters
Parameters are case-sensitive!
Notice that any of true, TRUE, True or 1 is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: false, FALSE, False or 0.
allowAllFiles
Type: bool
Valid Values: true, false
Default: false
allowAllFiles=true disables the file allowlist for LOAD DATA LOCAL INFILE and allows all files.
Might be insecure!
allowCleartextPasswords
Type: bool
Valid Values: true, false
Default: false
allowCleartextPasswords=true allows using the cleartext client side plugin if required by an account, such as one defined with the PAM authentication plugin. Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include TLS / SSL, IPsec, or a private network.
allowFallbackToPlaintext
Type: bool
Valid Values: true, false
Default: false
allowFallbackToPlaintext=true acts like a --ssl-mode=PREFERRED MySQL client as described in Command Options for Connecting to the Server
allowNativePasswords
Type: bool
Valid Values: true, false
Default: true
allowNativePasswords=false disallows the usage of MySQL native password method.
allowOldPasswords
Type: bool
Valid Values: true, false
Default: false
allowOldPasswords=true allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also the old_passwords wiki page.
charset
Type: string
Valid Values: <name>
Default: none
Sets the charset used for client-server interaction ("SET NAMES <value>"). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset fails. This enables for example support for utf8mb4 (introduced in MySQL 5.5.3) with fallback to utf8 for older servers (charset=utf8mb4,utf8).
See also Unicode Support.
checkConnLiveness
Type: bool
Valid Values: true, false
Default: true
On supported platforms connections retrieved from the connection pool are checked for liveness before using them. If the check fails, the respective connection is marked as bad and the query retried with another connection.
checkConnLiveness=false disables this liveness check of connections.
collation
Type: string
Valid Values: <name>
Default: utf8mb4_general_ci
Sets the collation used for client-server interaction on connection. In contrast to charset, collation does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail.
A list of valid charsets for a server is retrievable with SHOW COLLATION.
The default collation (utf8mb4_general_ci) is supported from MySQL 5.5. You should use an older collation (e.g. utf8_general_ci) for older MySQL.
Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used (ref).
See also Unicode Support.
clientFoundRows
Type: bool
Valid Values: true, false
Default: false
clientFoundRows=true causes an UPDATE to return the number of matching rows instead of the number of rows changed.
columnsWithAlias
Type: bool
Valid Values: true, false
Default: false
When columnsWithAlias is true, calls to sql.Rows.Columns() will return the table alias and the column name separated by a dot. For example:
SELECT u.id FROM users as u
will return u.id instead of just id if columnsWithAlias=true.
compress
Type: bool
Valid Values: true, false
Default: false
Toggles compression. false by default. Connections use zlib unless the optional
github.com/go-sql-driver/mysql/zstd package is imported:
import _ "github.com/go-sql-driver/mysql/zstd"
This import also registers the MySQL driver. With compress=true (or
EnableCompression(true)), connections automatically prefer zstd when the server
supports it and fall back to zlib otherwise.
Applications that do not import mysql/zstd do not compile or link
github.com/klauspost/compress. The optional package's dependency is listed in the
module's go.mod.
interpolateParams
Type: bool
Valid Values: true, false
Default: false
If interpolateParams is true, placeholders (?) in calls to db.Query() and db.Exec() are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with interpolateParams=false.
This can not be used together with the multibyte encodings BIG5, CP932, GB18030, GBK or SJIS. A charset or collation