简体   繁体   中英

MySQL: determine the value of max_allowed_packet for the client at runtime

Consider this situation:

-- Server: max_allowed_packet = 200MB 
-- Client: max_allowed_packet = 4MB

-- The following will return 200MB
SHOW variables like 'max_allowed_packet';

Without reading the configuration file, is it possible to determine the value of max_allowed_packet for the client? I'm using the MySQL C API.

Basically, I want my app to have something like:

 max_allowed_packet = min(max_allowed_packet_server, max_allowed_packet_client)

You cannot directly determine max_allowed_packet for client at run time. When you execute show variables like "max_allowed_packet" , it shows max_allowed_packet for server side only and that too whatever it read at start time. And there seems no other way to find this value.

Further, to solve your problem, by default, From MySQL Docs

On the client side, max_allowed_packet has a default of 1GB.

Moreover, as you have specified that you are using MySQL C API . You can set the value of max_allowed_packet, using mysql_options() API as follows:

First create your option file with content

[client]
max_allowed_packet=10M

Lets say this file is saved as "c:/mysql.cnf" which sets the value for max_allowed_packet for client as 10MB. Now what you need is to include following line of code to read this file before your connect statement.

mysql_options (conn, MYSQL_READ_DEFAULT_FILE, "C:/mysql.cnf");

if you wish to change name of group from client to myClient in file then, make your "c:/mysql.cnf" as

[myClient]
max_allowed_packet=10M

and use following line of codes before your connection statement:

mysql_options (conn, MYSQL_READ_DEFAULT_FILE, "c:/mysql.cnf");
mysql_options (conn, MYSQL_READ_DEFAULT_GROUP, "myClient");

So, finally your code will look something like this:

MYSQL mysql;

mysql_init(&mysql);
mysql_options (conn, MYSQL_READ_DEFAULT_FILE, "c:/mysql.cnf");
mysql_options (conn, MYSQL_READ_DEFAULT_GROUP, "myClient");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
}

Above line of code, will set your max_allowed_packet to 10M, now you can read server side max_allowed_packet using query " show variables like "max_allowed_packet" " and you know your client side max_allowed_packet as 10MB.

For further references 1

For MySQL Commandline client, MySQL docs says

If you are using the mysql client program, its default max_allowed_packet variable is 16MB

Hope it helps, and serves your purpose....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM