Documentation ¶
Overview ¶
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 _ "github.com/go-sql-driver/mysql" db, err := sql.Open("mysql", "user:password@/dbname")
See https://github.com/go-sql-driver/mysql#usage for details
Index ¶
- Variables
- func DeregisterLocalFile(filePath string)
- func DeregisterReaderHandler(name string)
- func DeregisterServerPubKey(name string)
- func DeregisterTLSConfig(key string)
- func NewConnector(cfg *Config) (driver.Connector, error)
- func RegisterDial(network string, dial DialFunc)deprecated
- func RegisterDialContext(net string, dial DialContextFunc)
- func RegisterLocalFile(filePath string)
- func RegisterReaderHandler(name string, handler func() io.Reader)
- func RegisterServerPubKey(name string, pubKey *rsa.PublicKey)
- func RegisterTLSConfig(key string, config *tls.Config) error
- func SetLogger(logger Logger) error
- type Config
- type DialContextFunc
- type DialFuncdeprecated
- type DumpConn
- func (mc DumpConn) Begin() (driver.Tx, error)
- func (mc DumpConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)
- func (mc DumpConn) CheckNamedValue(nv *driver.NamedValue) (err error)
- func (d *DumpConn) Close() error
- func (d *DumpConn) Exec(query string) error
- func (mc DumpConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)
- func (d *DumpConn) HandleErrorPacket(data []byte) error
- func (d *DumpConn) NoticeDump(serverID, offset uint32, filename string, flags uint16) error
- func (mc DumpConn) Ping(ctx context.Context) (err error)
- func (mc DumpConn) Prepare(query string) (driver.Stmt, error)
- func (mc DumpConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)
- func (mc DumpConn) Query(query string, args []driver.Value) (driver.Rows, error)
- func (mc DumpConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)
- func (d *DumpConn) ReadPacket() ([]byte, error)
- func (mc DumpConn) ResetSession(ctx context.Context) error
- type Logger
- type MySQLDriver
- type MySQLError
- type NullTime
Constants ¶
This section is empty.
Variables ¶
var ( PacketEOF = iEOF PacketOK = iOK PacketERR = iERR )
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("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") 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.
Functions ¶
func DeregisterLocalFile ¶
func DeregisterLocalFile(filePath string)
DeregisterLocalFile removes the given filepath from the whitelist.
func DeregisterReaderHandler ¶
func DeregisterReaderHandler(name string)
DeregisterReaderHandler removes the ReaderHandler function with the given name from the registry.
func DeregisterServerPubKey ¶ added in v1.4.0
func DeregisterServerPubKey(name string)
DeregisterServerPubKey removes the public key registered with the given name.
func DeregisterTLSConfig ¶ added in v1.1.0
func DeregisterTLSConfig(key string)
DeregisterTLSConfig removes the tls.Config associated with key.
func NewConnector ¶ added in v1.4.2
NewConnector returns new driver.Connector.
func RegisterDial
deprecated
added in
v1.2.0
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.
Deprecated: users should call RegisterDialContext instead
func RegisterDialContext ¶ added in v1.4.2
func RegisterDialContext(net string, dial DialContextFunc)
RegisterDialContext registers a custom dial function. It can then be used by the network address mynet(addr), where mynet is the registered new network. The current context for the connection and its address is passed to the dial function.
func RegisterLocalFile ¶
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" mysql.RegisterLocalFile(filePath) err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") if err != nil { ...
func RegisterReaderHandler ¶
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 RegisterServerPubKey ¶ added in v1.4.0
RegisterServerPubKey registers a server RSA public key which can be used to send data in a secure manner to the server without receiving the public key in a potentially insecure way from the server first. Registered keys can afterwards be used adding serverPubKey=<name> to the DSN.
Note: The provided rsa.PublicKey instance is exclusively owned by the driver after registering it and may not be modified.
data, err := ioutil.ReadFile("mykey.pem") if err != nil { log.Fatal(err) } block, _ := pem.Decode(data) if block == nil || block.Type != "PUBLIC KEY" { log.Fatal("failed to decode PEM block containing public key") } pub, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { log.Fatal(err) } if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { mysql.RegisterServerPubKey("mykey", rsaPubKey) } else { log.Fatal("not a RSA public key") }
func RegisterTLSConfig ¶ added in v1.1.0
RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. Use the key as a value in the DSN where tls=value.
Note: The provided tls.Config is exclusively owned by the driver after registering it.
rootCertPool := x509.NewCertPool() pem, err := ioutil.ReadFile("/path/ca-cert.pem") if err != nil { log.Fatal(err) } 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 { log.Fatal(err) } 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")
Types ¶
type Config ¶ added in v1.3.0
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 ServerPubKey string // Server public key name 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 RejectReadOnly bool // Reject read-only connections // contains filtered or unexported fields }
Config is a configuration parsed from a DSN string. If a new Config is created instead of being parsed from a DSN string, the NewConfig function should be used, which sets default values.
func NewConfig ¶ added in v1.4.0
func NewConfig() *Config
NewConfig creates a new Config and sets default values.
type DialContextFunc ¶ added in v1.4.2
DialContextFunc is a function which can be used to establish the network connection. Custom dial functions must be registered with RegisterDialContext
type DumpConn ¶ added in v1.4.2
type DumpConn struct {
// contains filtered or unexported fields
}
DumpConn dump协议获取binlog
func NewDumpConn ¶ added in v1.4.2
NewDumpConn 获取协议获取binlog
func (DumpConn) CheckNamedValue ¶ added in v1.4.2
func (mc DumpConn) CheckNamedValue(nv *driver.NamedValue) (err error)
func (DumpConn) ExecContext ¶ added in v1.4.2
func (*DumpConn) HandleErrorPacket ¶ added in v1.4.2
ReadPacket 处理回复包错误
func (*DumpConn) NoticeDump ¶ added in v1.4.2
NoticeDump 通知协议使用dump协议
func (DumpConn) PrepareContext ¶ added in v1.4.2
func (DumpConn) QueryContext ¶ added in v1.4.2
func (*DumpConn) ReadPacket ¶ added in v1.4.2
ReadPacket 读取binlog消息
func (DumpConn) ResetSession ¶ added in v1.4.2
ResetSession implements driver.SessionResetter. (From Go 1.10)
type Logger ¶ added in v1.2.0
type Logger interface {
Print(v ...interface{})
}
Logger is used to log critical error messages.
type MySQLDriver ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (d MySQLDriver) Open(dsn string) (driver.Conn, error)
Open new Connection. See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how the DSN string is formatted
func (MySQLDriver) OpenConnector ¶ added in v1.4.2
func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error)
OpenConnector implements driver.DriverContext.
type MySQLError ¶
MySQLError is an error type which represents a single MySQL error
func (*MySQLError) Error ¶
func (me *MySQLError) Error() string
type NullTime ¶
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