Some recommendations for using Perl DBI to operate MySQL

  • 2020-11-03 22:37:36
  • OfStack

Using perl to connect to mysql, there are many cases on the Internet, 1 generally everyone is under DBI DBD::MySQL this module. So let's do 1 mask and let's do 1 TIPS:
The character set of Perl DBI MySQL is UTF8
Perl DBI special character written wrong
Perl DBI connections automatically reconnect or connect timeout

1. When the character set of MySQL is UTF8, it is necessary to introduce:


use utf8;
binmode(STDOUT, ':encoding(utf8)');
binmode(STDIN, ':encoding(utf8)');
binmode(STDERR, ':encoding(utf8)');

Objective:
To solve the problem that perl connected mysql to the data after reading the display result is confused code.

2. For writing special characters, it is best to use:


 my $sth=$dbh->prepare("insert into wubx.WeekEvent values(?,?,?,?,?,?,?)");
 $sth->execute($OId,$CId,qq/$Time/,$EventType,qq/$CDesc/,$PId,$RFlag);


For strings that may be user-submitted packages with qq//, reduce the number of cases where special characters cause SQL to fail.
3. If there is an exchange or transfer of data between two databases, consider the case of repeated timeouts.
Error: MySQL server has gone away
Treatment:
Automatic reconnection of DBI connections is supported after DBD::mysql 4.012. Need to set:


 $dbh->{mysql_auto_reconnect} = 1;

Not supported in earlier modules, simple approach:


 $dbh->do('set SESSION wait_timeout=72000');
 $dbh->do('set SESSION interactive_timeout=72000') ; 

This method applies to other languages where the MySQL connection is temporarily lost or the timeout time setting of Server is too short.


Related articles: