wire / wire-format / mysql-protocol

MySQL protocol (packet structure)

MySQL's protocol is a packet-based TCP protocol. Each packet: 3-byte length (little-endian), 1-byte sequence number, then payload. The first packet from the server is the Handshake (protocol version, server version string, connection ID, auth plugin data, capabilities, status, character set). The client responds with a HandshakeResponse. Queries are sent as COM_QUERY packets (command byte 0x03 + SQL string).

wire-format kind wire-format status standard verification verified tier B wire-format@1

aka: MySQL protocol (packet structure)

wire format

spec: MySQL Internals Manual

MySQL's protocol is a packet-based TCP protocol. Each packet: 3-byte length (little-endian), 1-byte sequence number, then payload. The first packet from the server is the Handshake (protocol version, server version string, connection ID, auth plugin data, capabilities, status, character set). The client responds with a HandshakeResponse. Queries are sent as COM_QUERY packets (command byte 0x03 + SQL string).

fieldsizemeaning
Packet length3 bytes (little-endian)Length of the payload (max 16MB; larger payloads use multiple packets).
Sequence number1 bytePacket sequence number (increments per packet in a command; resets to 0 for new commands).
Payload= lengthCommand byte + data, or result set, or error packet.
Handshake (server -> client)variableProtocol version (1) + server version (NUL-terminated) + connection ID (4) + auth plugin data part 1 (8) + filler (1) + capability flags (2/4) + charset (1) + status (2) + auth plugin data length (1) + reserved (10) + auth plugin data part 2 + auth plugin name (NUL-terminated).
COM_QUERYvariableCommand byte 0x03 + SQL string (not NUL-terminated; length is the packet length).
OK packetvariableHeader 0x00 + affected rows (varint) + last insert ID (varint) + status flags (2) + warnings (2) + info string.
ERR packetvariableHeader 0xFF + error code (2) + SQL state marker '#' + SQL state (5) + error message.
EOF packet5 bytesHeader 0xFE + warnings (2) + status flags (2). (Deprecated in MySQL 5.7+; replaced by OK packet with 0xFE header.)

example:

13 00 00 00 03 53 45 4c 45 43 54 20 40 40 76 65 72 73 69 6f 6e

MySQL COM_QUERY packet: length 19, seq 0, command 0x03, SQL 'SELECT @@version'


provenance

agent: curl -H 'accept: application/json' wire.phall.io/wire-format/mysql-protocol or /wire-format/mysql-protocol.json