in reply to how to put this db connection code into a function

sub connect { return DBI->connect( "DBI:mysql:".join(';', "database=$sql_database", "host=$sql_host", "port=$sql_port", ), $username, $password, { RaiseError => 0, AutoCommit => 1, }, ); }; my $dbh = connect() or die("Can't connect: $DBI::errstr\n");

Replies are listed 'Best First'.
Re^2: how to put this db connection code into a function
by ikegami (Patriarch) on Jan 04, 2011 at 23:28 UTC

    I suppose the above leaves RaiseError in the wrong state for subsequent prepare and other calls. Fixed:

    sub connect { return eval { DBI->connect( "DBI:mysql:".join(';', "database=$sql_database", "host=$sql_host", "port=$sql_port", ), $username, $password, { RaiseError => 1, AutoCommit => 1, }, ) }; }; my $dbh = connect() or die("Can't connect: $DBI::errstr\n");
      i don't really want to use the $DBI::errstr as it returns far less information than what is in the $@ variable. That has the line number of the problem plus the statement that was executed, whereas DBI::errstr just has a limited error message
        sub connect { return DBI->connect( "DBI:mysql:".join(';', "database=$sql_database", "host=$sql_host", "port=$sql_port", ), $username, $password, { RaiseError => 1, AutoCommit => 1, }, ); } my $dbh = eval { connect() } or die("Can't connect: $@");