perl - DBIx::可以在重新连接时恢复 session 变量的东西?

标签 perl dbi

普通的 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/

相关文章:

linux - 安装 Perl 模块 MIME::Lite 时出错

java - 在 Perl 中使用文件参数执行 JAR 文件

perl - 如何将 Perl 调试器输出限制为我自己脚本中的行?

sql-server - 修剪数组(通过 DBI 填充)

perl - 可以连接两个使用不同输入记录分隔符的 Perl 脚本吗?

perl - 在 Perl 中循环两个日期的最佳方式是什么?

sql - 无法从 csv 文件中选择列

perl - 如何限制 DBIx::Error 中的堆栈跟踪?

PERL 5.8.4 安装 DBI 模块

mysql - 在 macOS Catalina 10.15.1 下安装 DBD::mysql 时遇到问题