brscvs has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have an old daemon code that connects to dbi(sqlite) in the beginning of the file and there is an infinite loop at bottom.

So my question is:

In the subroutines should I connect and disconnect the database every time , can connection gone ? if it does daemon fails. What is the best practice for this ?

I appreciate any help

Replies are listed 'Best First'.
Re: dbi connection daemon process
by 1nickt (Canon) on Jan 19, 2016 at 08:01 UTC

    Hi, please see How do I post a question effectively? -- it is much easier to help if we can see your code.

    In the subroutines should I connect and disconnect the database every +time

    No, you should not connect to the DB every time you call a sub, if you can help it: DB connections can be expensive.

    can connection gone ?

    You can open your DB connection and store the handle in a package variable:

    #!/usr/bin/perl use DBI; my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","",""); sub foo { my $sth = $dbh->prepare( $some_query ); $sth->execute; } sub bar { my $result = $dbh->do( $other_query ); }

    Or, for larger applications, see connect_cached() in the DBI documentation for a persistent DB connection handle.

    Hope this helps!


    update: showed alternative to connect_cached
    The way forward always starts with a minimal test.