普通的 DBI::db 处理程序将丢失所有使用 $dbh->do('SET variable_name=value') 进行的数据库 session 设置。
是否有任何 DBIx::* 类/包或提供类似“set_session”的方法来设置 session 变量,并可以在检测到连接丢失(90% 的实际情况下连接超时)后恢复此变量?
它可能看起来像这样:
# inside the user code:
$dbh->set(variable => 'string', yet_another_variable => 42)
# inside the DBIx::* package:
sub reconnect {
# ...
while (my ($var, $val) = each %{$self->saved_vars}) {
$self->dbh->do("SET $var=?", {}, $val)
}
# ...
}
最佳答案
DBI 支持 something called Callbacks .我无法链接到文档的这一部分,因为该部分很长,所以这里是逐字逐句的。
A more common application for callbacks is setting connection state only when a new connection is made (by connect() or connect_cached()). Adding a callback to the connected method (when using connect) or via connect_cached.connected (when useing connect_cached()>) makes this easy. The connected() method is a no-op by default (unless you subclass the DBI and change it). The DBI calls it to indicate that a new connection has been made and the connection attributes have all been set. You can give it a bit of added functionality by applying a callback to it. For example, to make sure that MySQL understands your application's ANSI-compliant SQL, set it up like so:
my $dbh = DBI->connect($dsn, $username, $auth, { Callbacks => { connected => sub { shift->do(q{ SET SESSION sql_mode='ansi,strict_trans_tables,no_auto_value_on_zero'; }); return; }, } });
我相信这正是您的用例。连接后执行此操作而不是运行您自己的代码。
关于perl - DBIx::可以在重新连接时恢复 session 变量的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430773/