mysql: Index | Files

package mysql

import ""

Package mysql provides a MySQL driver for Go's database/sql package.

The driver should be used via the database/sql package:

import "database/sql"
import _ ""

db, err := sql.Open("mysql", "user:password@/dbname")

See for details


Package Files

buffer.go collations.go connection.go const.go driver.go dsn.go errors.go infile.go packets.go result.go rows.go statement.go transaction.go utils.go


var (
    ErrInvalidConn       = errors.New("invalid connection")
    ErrMalformPkt        = errors.New("malformed packet")
    ErrNoTLS             = errors.New("TLS requested but server does not support TLS")
    ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN")
    ErrNativePassword    = errors.New("this user requires mysql native password authentication.")
    ErrOldPassword       = errors.New("" /* 191 byte string literal not displayed */)
    ErrUnknownPlugin     = errors.New("this authentication plugin is not supported")
    ErrOldProtocol       = errors.New("MySQL server does not support required protocol 41+")
    ErrPktSync           = errors.New("commands out of sync. You can't run this command now")
    ErrPktSyncMul        = errors.New("commands out of sync. Did you run multiple statements at once?")
    ErrPktTooLarge       = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server")
    ErrBusyBuffer        = errors.New("busy buffer")

Various errors the driver might return. Can change between driver versions.

func DeregisterLocalFile Uses

func DeregisterLocalFile(filePath string)

DeregisterLocalFile removes the given filepath from the whitelist.

func DeregisterReaderHandler Uses

func DeregisterReaderHandler(name string)

DeregisterReaderHandler removes the ReaderHandler function with the given name from the registry.

func DeregisterTLSConfig Uses

func DeregisterTLSConfig(key string)

DeregisterTLSConfig removes the tls.Config associated with key.

func RegisterDial Uses

func RegisterDial(net string, dial DialFunc)

RegisterDial registers a custom dial function. It can then be used by the network address mynet(addr), where mynet is the registered new network. addr is passed as a parameter to the dial function.

func RegisterLocalFile Uses

func RegisterLocalFile(filePath string)

RegisterLocalFile adds the given file to the file whitelist, so that it can be used by "LOAD DATA LOCAL INFILE <filepath>". Alternatively you can allow the use of all local files with the DSN parameter 'allowAllFiles=true'

filePath := "/home/gopher/data.csv"
err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo")
if err != nil {

func RegisterReaderHandler Uses

func RegisterReaderHandler(name string, handler func() io.Reader)

RegisterReaderHandler registers a handler function which is used to receive a io.Reader. The Reader can be used by "LOAD DATA LOCAL INFILE Reader::<name>". If the handler returns a io.ReadCloser Close() is called when the request is finished.

mysql.RegisterReaderHandler("data", func() io.Reader {
	var csvReader io.Reader // Some Reader that returns CSV data
	... // Open Reader here
	return csvReader
err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo")
if err != nil {

func RegisterTLSConfig Uses

func RegisterTLSConfig(key string, config *tls.Config) error

RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. Use the key as a value in the DSN where tls=value.

rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("/path/ca-cert.pem")
if err != nil {
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
    log.Fatal("Failed to append PEM.")
clientCert := make([]tls.Certificate, 0, 1)
certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem")
if err != nil {
clientCert = append(clientCert, certs)
mysql.RegisterTLSConfig("custom", &tls.Config{
    RootCAs: rootCertPool,
    Certificates: clientCert,
db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom")

func SetLogger Uses

func SetLogger(logger Logger) error

SetLogger is used to set the logger for critical errors. The initial logger is os.Stderr.

type Config Uses

type Config struct {
    User             string            // Username
    Passwd           string            // Password (requires User)
    Net              string            // Network type
    Addr             string            // Network address (requires Net)
    DBName           string            // Database name
    Params           map[string]string // Connection parameters
    Collation        string            // Connection collation
    Loc              *time.Location    // Location for time.Time values
    MaxAllowedPacket int               // Max packet size allowed
    TLSConfig        string            // TLS configuration name

    Timeout      time.Duration // Dial timeout
    ReadTimeout  time.Duration // I/O read timeout
    WriteTimeout time.Duration // I/O write timeout

    AllowAllFiles           bool // Allow all files to be used with LOAD DATA LOCAL INFILE
    AllowCleartextPasswords bool // Allows the cleartext client side plugin
    AllowNativePasswords    bool // Allows the native password authentication method
    AllowOldPasswords       bool // Allows the old insecure password method
    ClientFoundRows         bool // Return number of matching rows instead of rows changed
    ColumnsWithAlias        bool // Prepend table alias to column names
    InterpolateParams       bool // Interpolate placeholders into query string
    MultiStatements         bool // Allow multiple statements in one query
    ParseTime               bool // Parse time values to time.Time
    Strict                  bool // Return warnings as errors
    // contains filtered or unexported fields

Config is a configuration parsed from a DSN string

func ParseDSN Uses

func ParseDSN(dsn string) (cfg *Config, err error)

ParseDSN parses the DSN string to a Config

func (*Config) FormatDSN Uses

func (cfg *Config) FormatDSN() string

FormatDSN formats the given Config into a DSN string which can be passed to the driver.

type DialFunc Uses

type DialFunc func(addr string) (net.Conn, error)

DialFunc is a function which can be used to establish the network connection. Custom dial functions must be registered with RegisterDial

type Logger Uses

type Logger interface {
    Print(v ...interface{})

Logger is used to log critical error messages.

type MySQLDriver Uses

type MySQLDriver struct{}

MySQLDriver is exported to make the driver directly accessible. In general the driver is used via the database/sql package.

func (MySQLDriver) Open Uses

func (d MySQLDriver) Open(dsn string) (driver.Conn, error)

Open new Connection. See for how the DSN string is formated

type MySQLError Uses

type MySQLError struct {
    Number  uint16
    Message string

MySQLError is an error type which represents a single MySQL error

func (*MySQLError) Error Uses

func (me *MySQLError) Error() string

type MySQLWarning Uses

type MySQLWarning struct {
    Level   string
    Code    string
    Message string

MySQLWarning is an error type which represents a single MySQL warning. Warnings are returned in groups only. See MySQLWarnings

type MySQLWarnings Uses

type MySQLWarnings []MySQLWarning

MySQLWarnings is an error type which represents a group of one or more MySQL warnings

func (MySQLWarnings) Error Uses

func (mws MySQLWarnings) Error() string

type NullTime Uses

type NullTime struct {
    Time  time.Time
    Valid bool // Valid is true if Time is not NULL

NullTime represents a time.Time that may be NULL. NullTime implements the Scanner interface so it can be used as a scan destination:

var nt NullTime
err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
if nt.Valid {
   // use nt.Time
} else {
   // NULL value

This NullTime implementation is not driver-specific

func (*NullTime) Scan Uses

func (nt *NullTime) Scan(value interface{}) (err error)

Scan implements the Scanner interface. The value type must be time.Time or string / []byte (formatted time-string), otherwise Scan fails.

func (NullTime) Value Uses

func (nt NullTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

Package mysql imports 19 packages (graph) and is imported by 2418 packages. Updated 2017-05-20. Refresh now. Tools for package owners.