MCPcopy
hub / github.com/go-sql-driver/mysql

github.com/go-sql-driver/mysql @v1.10.0 sqlite

repository ↗ · DeepWiki ↗ · release v1.10.0 ↗
489 symbols 2,098 edges 35 files 159 documented · 33%
README

Go-MySQL-Driver

DeepWiki

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

Go-MySQL-Driver logo



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.

Requirements

  • Go 1.24 or higher. We aim to support the 3 latest versions of Go.
  • MySQL (5.7+) and MariaDB (10.5+) 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&...&paramN=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 zlib compression. false by default.

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, GB2312, GBK or SJIS. These are rejected as they may introduce a SQL injection vulnerability!

loc
Type:           string
Valid Values:   <escaped name>
Default:        UTC

Sets the location for time.Time values (when using parseTime=true). "Local" sets the system's location. See time.LoadLocation for details.

Note that this sets the location for time.Time values but does not change MySQL's time_zone setting. For that see the time_zone system variable, which can also be set as a DSN parameter.

Please keep in mind, that param values must be url.QueryEscape'ed. Alternatively you can manually replace the / with %2F. For example US/Pacific would be loc=US%2FPacific.

timeTruncate
Type:           duration
Default:        0

Truncate time values to the specified duration. The value mu

Extension points exported contracts — how you extend this code

Result (Interface)
Result exposes data not available through *connection.Result. This is accessible by executing statements using sql.Conn [1 …
result.go
Logger (Interface)
Logger is used to log critical error messages. [1 implementers]
errors.go
Option (FuncType)
Functional Options Pattern https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
dsn.go
DialFunc (FuncType)
DialFunc is a function which can be used to establish the network connection. Custom dial functions must be registered w
driver.go
DialContextFunc (FuncType)
DialContextFunc is a function which can be used to establish the network connection. Custom dial functions must be regis
driver.go

Core symbols most depended-on inside this repo

Scan
called by 82
nulltime.go
Next
called by 62
rows.go
Error
called by 37
errors.go
handleAuthResult
called by 36
auth.go
ParseDSN
called by 32
dsn.go
Close
called by 31
rows.go
Exec
called by 30
statement.go
writeDSNParam
called by 24
dsn.go

Shape

Function 270
Method 168
Struct 35
TypeAlias 10
FuncType 4
Interface 2

Languages

Go100%

Modules by API surface

driver_test.go107 symbols
auth_test.go40 symbols
utils.go36 symbols
connection.go35 symbols
packets.go31 symbols
connection_test.go23 symbols
benchmark_test.go23 symbols
rows.go17 symbols
packets_test.go15 symbols
dsn.go15 symbols
auth.go15 symbols
dsn_test.go13 symbols

Dependencies from manifests, versioned

filippo.io/edwards25519v1.2.0 · 1×

For agents

$ claude mcp add mysql \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact