[英]DBIx::Class get the dbh
I'm using DBIx::Class in a Catalyst app I am building. 我在我正在构建的Catalyst应用程序中使用DBIx :: Class 。 It works great, but sometimes I need to use my own db functions that I've developed that are very specific to my needs.
它工作得很好,但有时我需要使用我自己开发的自己的db函数,这些函数非常符合我的需求。 Because of this, I need a dbh.
因此,我需要一个dbh。 However, since I'm already using
DBIx::Class
I know that it already has a dbh that it is using. 但是,因为我已经在使用
DBIx::Class
,所以我知道它已经使用了dbh。 To avoid making another unnecessary connection to the database, I would like to just use the dbh that DBIx::Class
has already created. 为了避免与数据库建立另一个不必要的连接,我想使用
DBIx::Class
已经创建的dbh。 I know that the DBIx::Class::Storage::DBI module has two methods dbh
and dbh_do
, but I'm not really sure what the difference is between the two and if they are the best way to get access to the dbh. 我知道DBIx :: Class :: Storage :: DBI模块有两个方法
dbh
和dbh_do
,但我不确定两者之间的区别是什么,以及它们是否是访问dbh的最佳方式。 Can anyone tell me what the best way to get the dbh from DBIx::Class
would be in a Catalyst
app? 任何人都可以告诉我从
DBIx::Class
获取dbh的最佳方法是在Catalyst
应用程序中吗? I'd prefer a method that I could forward to that would store the dbh in the stash like below: 我更喜欢一种方法,我可以将其存储在存储区中,如下所示:
sub dbh :Private {
my ($self, $c) = @_;
$c->stash->{dbh} = #get dbh from DBIx::Class here
}
Thanks! 谢谢!
I always have to look this up. 我总是要看一下。 Assuming you have an instance of your schema object, you can get its Storage object via the
storage
method. 假设您有一个架构对象的实例,您可以通过
storage
方法获取其Storage对象。 Assuming that's a Storage::DBI
, then there is a dbh
method available which will get you your database handle. 假设这是一个
Storage::DBI
,那么有一个dbh
方法可用于获取数据库句柄。 So: 所以:
my $dbh = $c->model( 'My::DB' )->storage->dbh;
should do the trick. 应该做的伎俩。
@srchulo Answers are great and dbh_do is way to go for it's inbuilt exception handling but I will advice to convert your function to rather not use dbh anymore and just work with DBIX::Class. @srchulo答案很棒,dbh_do是内置异常处理的方法,但我建议将你的函数转换为不再使用dbh而只是使用DBIX :: Class。 That way, next time, you just have to change at one place and not keep looking for legacy dbh and raw sqls.
这样,下次你只需要改变一个地方而不是继续寻找遗留的dbh和raw sqls。 Hope it makes sense.
希望它有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.